using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing.Design;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Workflow.Runtime.Tracking;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.CSharp;
using System.Linq;
using OpenComposite.Base;
using OpenComposite.Base.Collections;
using OpenComposite.HumanActivity.Contracts.Participants;
using OpenComposite.Mapper;
using OpenComposite.Workflow.Extenders;
using OpenComposite.EII.CodeGenerators;
using OpenComposite.EII.Interfaces;
using OpenComposite.EII.Repository;
using OpenComposite.EII.Services;
using OpenComposite.Workflow;
using OpenComposite.Workflow.Services;
using WeifenLuo.WinFormsUI.Docking;

namespace OpenComposite.EII.Designer.Workflow
{
	/// <summary>
	/// The custom workflow designer loader to load workflows from the Open Composite database.
	/// </summary>
	internal sealed class WorkflowLoader : WorkflowDesignerLoader
	{
		#region Initialization
		/// <summary>
		/// Initializes a new instance of the <see cref="WorkflowLoader"/> class.
		/// </summary>
		/// <param name="workflow">The workflow.</param>
		/// <param name="controller">The controller.</param>
		internal WorkflowLoader(Repository.Workflow workflow, WorkflowController controller)
		{
			_workflow = workflow;
			_controller = controller;
			this.ClassName = RepositoryService.GetIdentifier(_workflow.Name);
			if ( _workflow.ExtendedProperties.NamespaceCode == this.DefaultNamespace ||
				 string.IsNullOrEmpty(_workflow.ExtendedProperties.NamespaceCode) ) {
				this.Namespace = string.Format("{0}.{1}", this.DefaultNamespace, this.ClassName);
			} else {
				this.Namespace = _workflow.ExtendedProperties.NamespaceCode;
			}

			_showErrorMsgs = true;

			init();
		}
		private void init()
		{
			_listRuleIDs = new List<int>();
			_listLogActs = new List<int>();
			_listRuleConstIDs = new List<int>();

			#region create the code beside code compile unit
			codeBesideccu = new CodeCompileUnit();
			codeBesideccu.ReferencedAssemblies.Add("System.Workflow.Activities");

			CodeNamespace ns = new CodeNamespace(this.Namespace);
			ns.Imports.Add(new CodeNamespaceImport("System"));
			ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
			ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel.Design"));
			ns.Imports.Add(new CodeNamespaceImport("System.Workflow.ComponentModel.Design"));
			ns.Imports.Add(new CodeNamespaceImport("System.Workflow.ComponentModel"));
			ns.Imports.Add(new CodeNamespaceImport("System.Workflow.ComponentModel.Serialization"));
			ns.Imports.Add(new CodeNamespaceImport("System.Workflow.ComponentModel.Compiler"));
			ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
			ns.Imports.Add(new CodeNamespaceImport("System.Collections"));
			ns.Imports.Add(new CodeNamespaceImport("System.Workflow.Activities"));
			ns.Imports.Add(new CodeNamespaceImport("System.Workflow.ComponentModel"));
			ns.Imports.Add(new CodeNamespaceImport("System.Workflow.Runtime"));
			ns.Imports.Add(new CodeNamespaceImport(this.NamespaceData));

			codeBesideccu.Namespaces.Add(ns);

			_ctdBeside = new CodeTypeDeclaration(this.ClassName);
			if ( this.Workflow.Type == WorkflowType.Business_Process ||
				 this.Workflow.Type == WorkflowType.Mashup_Horizontal ) {
				_ctdBeside.BaseTypes.Add(typeof(OpenComposite.Workflow.HorizontalWorkflowActivity));
			} else {
				_ctdBeside.BaseTypes.Add(typeof(System.Workflow.Activities.SequentialWorkflowActivity));
			}
			_ctdBeside.BaseTypes.Add(this.OrchestrationInterfaceName);
			_ctdBeside.IsPartial = true;
			_ctdBeside.Attributes = MemberAttributes.Public;

			ns.Types.Add(_ctdBeside);
			#endregion

			_codeLogActivities = new CodeCompileUnit();
			_codeServices = new CodeCompileUnit();
			_codeMapping = new CodeCompileUnit();
			_codeRules = new CodeCompileUnit();
			_codeData = new CodeCompileUnit();
			_codeContracts = new CodeCompileUnit();
			_codeInterface = new CodeCompileUnit();
			_codeLocalService = new CodeCompileUnit();
			_codeHostService = new CodeCompileUnit();
			_codeWFInterface = new CodeCompileUnit();

			initCompileUnits(false);

		}
		private void initCompileUnits(bool simpleGenerate)
		{
			#region initialize code beside
			bool configMapping = Workflow.IsConfigurable ||
								 Workflow.IsConfigurable;
			bool configRules = Workflow.IsConfigurable;
			if ( configMapping || configRules ) {
				if ( _methodBesideInit == null ) {
					// add Initialize override
					_methodBesideInit = new CodeMemberMethod();
					_methodBesideInit.Attributes = MemberAttributes.Family | MemberAttributes.Override;
					_methodBesideInit.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Initialization"));
					_methodBesideInit.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Initialization"));
					_methodBesideInit.Name = "Initialize";
					_methodBesideInit.Parameters.Add(
						new CodeParameterDeclarationExpression(typeof(IServiceProvider), "provider"));
					if ( configMapping ) {
						_methodBesideInit.Statements.Add(
							new CodeAssignStatement(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), "_mapping"),
								new CodeObjectCreateExpression(this.Namespace + ".Mapping")));
					}
					if ( configRules ) {
						_methodBesideInit.Statements.Add(
							new CodeAssignStatement(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), "_rules"),
								new CodeObjectCreateExpression(this.NamespaceRules + ".Rules")));
					}
					_methodBesideInit.Statements.Add(new CodeCommentStatement("call base initialization"));
					_methodBesideInit.Statements.Add(
						new CodeMethodInvokeExpression(
							new CodeBaseReferenceExpression(),
							"Initialize",
							new CodeArgumentReferenceExpression("provider")));
					_ctdBeside.Members.Add(_methodBesideInit);
				}
			} else if ( _methodBesideInit != null ) {
				_ctdBeside.Members.Remove(_methodBesideInit);
				_methodBesideInit = null;
			}
			// add fields and properties for Rules and Mapping class
			if ( configMapping && _fieldBesideMapping == null ) {
				_fieldBesideMapping = new CodeMemberField(this.Namespace + ".Mapping", "_mapping");
				_ctdBeside.Members.Add(_fieldBesideMapping);
			} else if ( !configMapping && _fieldBesideMapping != null ) {
				_ctdBeside.Members.Remove(_fieldBesideMapping);
				_fieldBesideMapping = null;
			}
			if ( configRules && _fieldBesideRules == null ) {
				_fieldBesideRules = new CodeMemberField(this.NamespaceRules + ".Rules", "_rules");
				_ctdBeside.Members.Add(_fieldBesideRules);
			} else if ( !configRules && _fieldBesideRules != null ) {
				_ctdBeside.Members.Remove(_fieldBesideRules);
				_fieldBesideRules = null;
			}
			if ( configMapping && _propBesideMapping == null ) {
				_propBesideMapping = new CodeMemberProperty();
				_propBesideMapping.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				_propBesideMapping.HasGet = true;
				_propBesideMapping.HasSet = false;
				_propBesideMapping.Type = new CodeTypeReference(this.Namespace + ".Mapping");
				_propBesideMapping.Name = "Mapping";
				_propBesideMapping.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), "_mapping")));
				_ctdBeside.Members.Add(_propBesideMapping);
			} else if ( !configMapping && _propBesideMapping != null ) {
				_ctdBeside.Members.Remove(_propBesideMapping);
				_propBesideMapping = null;
			}
			if ( configRules && _propBesideRules == null ) {
				_propBesideRules = new CodeMemberProperty();
				_propBesideRules.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				_propBesideRules.HasGet = true;
				_propBesideRules.HasSet = false;
				_propBesideRules.Type = new CodeTypeReference(this.NamespaceRules + ".Rules");
				_propBesideRules.Name = "Rules";
				_propBesideRules.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), "_rules")));
				_ctdBeside.Members.Add(_propBesideRules);
			} else if ( !configRules && _propBesideRules != null ) {
				_ctdBeside.Members.Remove(_propBesideRules);
				_propBesideRules = null;
			}
			#endregion

			#region create logical activity class code compile unit
			_codeLogActivities.Namespaces.Clear();
			CodeNamespace nsLogAct = new CodeNamespace(this.Namespace);
			nsLogAct.Imports.Add(new CodeNamespaceImport("System"));
			nsLogAct.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
			nsLogAct.Imports.Add(new CodeNamespaceImport("System.Text"));
			_codeLogActivities.Namespaces.Add(nsLogAct);
			_ctdLogActs = new CodeTypeDeclaration("LogicalActivities");
			_ctdLogActs.Attributes = MemberAttributes.Public;
			_ctdLogActs.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
			CodeConstructor ctorLogAct = new CodeConstructor();
			ctorLogAct.Attributes = MemberAttributes.Public;
			ctorLogAct.Parameters.Add(new CodeParameterDeclarationExpression(
										new CodeTypeReference(this.ClassName), "orchestration"));
			ctorLogAct.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_orchestration"),
					new CodeArgumentReferenceExpression("orchestration")));
			_ctdLogActs.Members.Add(ctorLogAct);
			_ctdLogActs.Members.Add(new CodeMemberField(new CodeTypeReference(this.ClassName), "_orchestration"));
			nsLogAct.Types.Add(_ctdLogActs);
			#endregion

			if ( !simpleGenerate ) {
				#region create the service code compile unit
				_codeServices.Namespaces.Clear();
				CodeNamespace nsServices = new CodeNamespace(this.Namespace);
				nsServices.Imports.Add(new CodeNamespaceImport("System"));
				nsServices.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
				nsServices.Imports.Add(new CodeNamespaceImport("System.Text"));
				nsServices.Imports.Add(new CodeNamespaceImport("System.Web.Services"));
				nsServices.Imports.Add(new CodeNamespaceImport("System.ServiceModel"));
				nsServices.Imports.Add(new CodeNamespaceImport("System.Diagnostics"));
				nsServices.Imports.Add(new CodeNamespaceImport("OpenComposite.HumanActivity.Contracts.Participants"));
				_codeServices.Namespaces.Add(nsServices);
				_ctdServices = new CodeTypeDeclaration("ServiceCalls");
				_ctdServices.Attributes = MemberAttributes.Public;
				_ctdServices.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
				// add contructor
				CodeConstructor ctorServices = new CodeConstructor();
				ctorServices.Attributes = MemberAttributes.Public;
				ctorServices.Parameters.Add(new CodeParameterDeclarationExpression(
					new CodeTypeReference(this.OrchestrationInterfaceName), "orchestration"));
				ctorServices.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_orchestration"),
						new CodeArgumentReferenceExpression("orchestration")));
				_ctdServices.Members.Add(ctorServices);
				// add _orchestration member field
				_ctdServices.Members.Add(new CodeMemberField(new CodeTypeReference(this.OrchestrationInterfaceName), "_orchestration"));
				nsServices.Types.Add(_ctdServices);
				#endregion

				#region create mapping code compile unit
				_codeMapping.Namespaces.Clear();
				CodeNamespace nsMapping = new CodeNamespace(this.Namespace);
				nsMapping.Imports.Add(new CodeNamespaceImport("System"));
				nsMapping.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
				nsMapping.Imports.Add(new CodeNamespaceImport("System.Text"));
				nsMapping.Imports.Add(new CodeNamespaceImport(NamespaceData));
				nsMapping.Imports.Add(new CodeNamespaceImport("System.Xml"));
				nsMapping.Imports.Add(new CodeNamespaceImport("OpenComposite.Base"));
				nsMapping.Imports.Add(new CodeNamespaceImport("System.Data"));
				nsMapping.Imports.Add(new CodeNamespaceImport("System.IO"));
				_codeMapping.Namespaces.Add(nsMapping);
				_ctdMapping = new CodeTypeDeclaration("Mapping");
				_ctdMapping.Attributes = MemberAttributes.Public;
				_ctdMapping.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
				nsMapping.Types.Add(_ctdMapping);
				if ( _workflow.IsConfigurable ||
					 _workflow.IsConfigurable ) {
					_ctorMapping = new CodeConstructor();
					_ctorMapping.Attributes = MemberAttributes.Public;
					_ctdMapping.Members.Add(_ctorMapping);
				} else {
					_ctorMapping = null;
				}
				#endregion
			}

			#region create rules code compile unit
			_codeRules.Namespaces.Clear();
			CodeNamespace nsRules = new CodeNamespace(this.NamespaceRules);
			nsRules.Imports.Add(new CodeNamespaceImport("System"));
			nsRules.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
			nsRules.Imports.Add(new CodeNamespaceImport("System.Text"));
			_codeRules.Namespaces.Add(nsRules);
			_ctdRules = new CodeTypeDeclaration("Rules");
			_ctdRules.Attributes = MemberAttributes.Public;
			_ctdRules.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
			nsRules.Types.Add(_ctdRules);
			#endregion

			#region create data code compile unit
			_codeData.Namespaces.Clear();
			CodeNamespace nsData = new CodeNamespace(this.NamespaceData);
			nsData.Imports.Add(new CodeNamespaceImport("System"));
			nsData.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
			nsData.Imports.Add(new CodeNamespaceImport("System.Text"));
			nsData.Imports.Add(new CodeNamespaceImport("System.Xml.Serialization"));
			_codeData.Namespaces.Add(nsData);
			#endregion

			if ( !simpleGenerate ) {
				#region create contracts code compile unit
				_codeContracts.Namespaces.Clear();
				_codeContracts.AssemblyCustomAttributes.Clear();
				#endregion
			}

			#region create orchestration interface compile unit
			_codeInterface.Namespaces.Clear();
			CodeNamespace nsInterface = new CodeNamespace(this.Namespace);
			nsInterface.Imports.Add(new CodeNamespaceImport("System"));
			nsInterface.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
			nsInterface.Imports.Add(new CodeNamespaceImport("System.Text"));
			_codeInterface.Namespaces.Add(nsInterface);
			_ctdInterface = new CodeTypeDeclaration(this.InterfaceName);
			_ctdInterface.Attributes = MemberAttributes.Public;
			_ctdInterface.IsInterface = true;

			if ( this.Workflow.BuildType == WorkflowBuildType.WCF_IIS ||
				 this.Workflow.BuildType == WorkflowBuildType.WCF_WindowsForm ) {
				// IF WCF OR Mashup
				_ctdInterface.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(ServiceContractAttribute)),
						new CodeAttributeArgument(
							"CallbackContract",
							new CodeTypeOfExpression(this.CallbackInterfaceName)),
						new CodeAttributeArgument(
							"Namespace",
							new CodePrimitiveExpression(
								string.IsNullOrEmpty(this.Workflow.XmlNamespace) ?
									"http://www.theopencomposite.com/canonical_document" :
									this.Workflow.XmlNamespace))));

				_ctdInterfaceCallback = new CodeTypeDeclaration(this.CallbackInterfaceName);
				_ctdInterfaceCallback.Attributes = MemberAttributes.Public;
				_ctdInterfaceCallback.IsInterface = true;
				_ctdInterfaceCallback.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(ServiceContractAttribute)),
						new CodeAttributeArgument(
							"Namespace",
							new CodePrimitiveExpression(
								string.IsNullOrEmpty(this.Workflow.XmlNamespace) ?
									"http://www.theopencomposite.com/canonical_document" :
									this.Workflow.XmlNamespace))));

				nsInterface.Types.Add(_ctdInterfaceCallback);

			}
			nsInterface.Types.Add(_ctdInterface);
			#endregion

			#region create local service interface & implementation
			_codeLocalService.Namespaces.Clear();
			_nsLocalService = new CodeNamespace(this.Namespace);
			//_nsLocalService.Imports.Add(new CodeNamespaceImport("System"));
			//_nsLocalService.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
			//_nsLocalService.Imports.Add(new CodeNamespaceImport("System.Text"));
			_codeLocalService.Namespaces.Add(_nsLocalService);

			// local interface
			_ctdLocalInterface = new CodeTypeDeclaration("I" + this.ClassName + Deployment.cProxy);
			_ctdLocalInterface.Attributes = MemberAttributes.Public;
			_ctdLocalInterface.IsInterface = true;
			_ctdLocalInterface.CustomAttributes.Add(
				new CodeAttributeDeclaration(
					new CodeTypeReference(typeof(ExternalDataExchangeAttribute))));
			_nsLocalService.Types.Add(_ctdLocalInterface);

			// local service
			_ctdLocalService = new CodeTypeDeclaration(this.ClassName + Deployment.cProxy);
			_ctdLocalService.Attributes = MemberAttributes.Public;
			_ctdLocalService.BaseTypes.Add(_ctdLocalInterface.Name);
			_nsLocalService.Types.Add(_ctdLocalService);
			#endregion

			#region create host service code compile unit
			_codeHostService.Namespaces.Clear();
			CodeNamespace nsHostEmpty = new CodeNamespace();
			nsHostEmpty.Imports.Add(new CodeNamespaceImport("System"));
			nsHostEmpty.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
			nsHostEmpty.Imports.Add(new CodeNamespaceImport("System.Runtime.Serialization"));
			nsHostEmpty.Imports.Add(new CodeNamespaceImport("System.ServiceModel"));
			nsHostEmpty.Imports.Add(new CodeNamespaceImport("System.Text"));
			nsHostEmpty.Imports.Add(new CodeNamespaceImport(this.Namespace));
			nsHostEmpty.Imports.Add(new CodeNamespaceImport(this.NamespaceData));

			_ctdHostService = new CodeTypeDeclaration();
			_ctdHostService.Attributes = MemberAttributes.Public;
			_ctdHostService.BaseTypes.Add("I" + this.ClassName);
			_ctdHostService.CustomAttributes.Add(
				new CodeAttributeDeclaration(
					new CodeTypeReference(typeof(ServiceBehaviorAttribute)),
					new CodeAttributeArgument(
						"Namespace",
						new CodePrimitiveExpression(
							string.IsNullOrEmpty(this.Workflow.XmlNamespace) ?
							"http://www.theopencomposite.com/canonical_document" : this.Workflow.XmlNamespace)),
					new CodeAttributeArgument(
						"InstanceContextMode",
						new CodeFieldReferenceExpression(
							new CodeTypeReferenceExpression(typeof(InstanceContextMode)),
							"PerSession"))));
			_ctdHostService.Name = this.ClassName + "Service";

			nsHostEmpty.Types.Add(_ctdHostService);

			_codeHostService.Namespaces.Add(nsHostEmpty);
			#endregion

			#region create orchstration interface code compile unit
			// create namespace
			_codeWFInterface.Namespaces.Clear();
			CodeNamespace nsWFInterface = new CodeNamespace(this.Namespace);
			_codeWFInterface.Namespaces.Add(nsWFInterface);
			// create interface
			_ctdWFInterface = new CodeTypeDeclaration(this.OrchestrationInterfaceName);
			_ctdWFInterface.IsInterface = true;
			_ctdWFInterface.Attributes = MemberAttributes.Public;
			nsWFInterface.Types.Add(_ctdWFInterface);
			// add generic properties
			addPropertyToInterface(_ctdWFInterface, typeof(Guid), "InstanceId", true, true);
			addPropertyToInterface(_ctdWFInterface, typeof(bool), "IsDocumentFlowSimulation", true, true);
			addPropertyToInterface(_ctdWFInterface, typeof(bool), "IsSimulation", true, true);
			addPropertyToInterface(_ctdWFInterface, typeof(bool), "SimulateAllLogicalActivities", true, true);
			// add properties for rules and mapping
			if ( configRules ) {
				addPropertyToInterface(_ctdWFInterface, "Rules", "Rules", true, false);
			}
			if ( configMapping ) {
				addPropertyToInterface(_ctdWFInterface, "Mapping", "Mapping", true, false);
			}
			#endregion
		}

		#endregion

		#region Overrides from WorkflowDesignerLoader
		/// <summary>
		/// Initializes the <see cref="T:System.Workflow.ComponentModel.Design.WorkflowDesignerLoader"/> with any services required by the designer loader host.
		/// </summary>
		protected override void Initialize()
		{
			base.Initialize();

			// Add all the services to the loaderhost
			IDesignerLoaderHost host = LoaderHost;
			if ( host != null ) {
				this.SetBaseComponentClassName(this.FullClassName);
				// replace IMenuCommandService
				if ( host.GetService(typeof(IMenuCommandService)) != null )
					host.RemoveService(typeof(IMenuCommandService));
				host.AddService(typeof(IMenuCommandService), new WorkflowMenuCommandService(host, this));
				// replace IToolboxService
				//if ( host.GetService(typeof(IToolboxService)) != null )
				//    host.RemoveService(typeof(IToolboxService));
				//host.AddService(typeof(IToolboxService), new ToolboxService(host));

				TypeProvider typeProvider = new TypeProvider(host);

				typeProvider.AddCodeCompileUnit(this.CodeBesideCCU);
				typeProvider.AddCodeCompileUnit(this.LogicalActivitiesCCU);
				typeProvider.AddCodeCompileUnit(this.ServicesCCU);
				typeProvider.AddCodeCompileUnit(this.MappingCCU);
				typeProvider.AddCodeCompileUnit(this.RulesCCU);
				typeProvider.AddCodeCompileUnit(this.DataCCU);
				typeProvider.AddCodeCompileUnit(this.ContractsCCU);
				typeProvider.AddCodeCompileUnit(this.InterfaceCCU);

				typeProvider.AddAssemblyReference(typeof(System.EventHandler).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(System.ComponentModel.AttributeCollection).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(System.Workflow.ComponentModel.CompositeActivity).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(System.Workflow.Activities.SequentialWorkflowActivity).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(System.Runtime.Serialization.XsdDataContractImporter).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(System.ServiceModel.EndpointAddress).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(System.Web.Services.WebService).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(System.Xml.XmlDocument).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(OpenComposite.Base.Structures.RepositoryInformationAttribute).Assembly.Location);
				typeProvider.AddAssemblyReference(typeof(OpenComposite.Workflow.LogicalEPActivity).Assembly.Location);

				host.AddService(typeof(ITypeProvider), typeProvider, false);

				_memberCreation = new MemberCreationService(host, this);
				host.AddService(typeof(IMemberCreationService), _memberCreation);

				host.AddService(typeof(IPropertyValueUIService), new PropertyValueUIService());
				host.AddService(typeof(IEventBindingService), new EventBindingService(host, this));
				//host.AddService(typeof(IEventBindingService), new DefaultEventBindingService(host, this));
				host.AddService(typeof(IExtendedUIService), new ExtendedUIService(host));
				host.AddService(typeof(PropertyGrid), _controller.PropertyGrid);
				// replace IIdentifierCreationService
				//if ( host.GetService(typeof(IIdentifierCreationService)) != null )
				//    host.RemoveService(typeof(IIdentifierCreationService));
				//host.AddService(typeof(IIdentifierCreationService), new IdentifierCreationService(host));

				_memberCreation.CreateProperty(this.FullClassName,
											   "LogicalActivitiesClass",
											   typeProvider.GetType(this.Namespace + ".LogicalActivities"),
											   null,
											   true,
											   false,
											   false,
											   null,
											   true);
				initLogicalActivitiesClassProperty(typeProvider);

				//
				if ( host.GetService(typeof(DockPanel)) == null ) {
					host.AddService(typeof(DockPanel), _controller.DockPanel);
				}
				//
				if ( host.GetService(typeof(ITaskListService)) == null ) {
					host.AddService(typeof(ITaskListService), new TaskErrorListService(host));
				}
				host.AddService(typeof(IWorkflowValidator), new WorkflowValidator(host));

				IRepositoryChangeService repchange = host.GetService(typeof(IRepositoryChangeService)) as IRepositoryChangeService;
				if ( repchange != null ) {
					repchange.RepositoryChanged += new RepositoryChangedEventHandler(repchange_RepositoryChanged);
				}
				IComponentChangeService compchange = host.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
				if ( compchange != null ) {
					compchange.ComponentChanged += new ComponentChangedEventHandler(compchange_ComponentChanged);
				}

			}
		}

		private void compchange_ComponentChanged(object sender, ComponentChangedEventArgs e)
		{
			if ( e.NewValue != e.OldValue ) _controller.IsChanged = true;
			ExtendedCodeActivity code = e.Component as ExtendedCodeActivity;
			if ( code != null ) {
				if ( e.Member.Name == "Name" ) {
					foreach ( Repository.Workflow.MethodCodeSnippet method in _workflow.ExtendedProperties.MethodCodeSnippets ) {
						if ( method.ActivityName == e.OldValue.ToString() ) {
							method.ActivityName = e.NewValue.ToString();
						}
					}
				}
			}
			//ILogicalActivity logact = e.Component as ILogicalActivity;
			//if ( logact != null && e.Member.Name == "LogicalActivityId" ) {

			//}
		}

		private void repchange_RepositoryChanged(object sender, RepositoryChangedEventArgs e)
		{
			if ( e.RepositoryItem == null || e.Member == null ) return;	// EXIT

			Debug.WriteLine(string.Format("[RepChanged] ItemType: {0} Name: {1} Member: {2}",
				e.RepositoryItem.RepositoryItemTypeName, e.RepositoryItem.Name, e.Member.Name));

			if ( e.RepositoryItem is WorkflowEvent || e.RepositoryItem is WorkflowMethod ) {
				if ( e.Member.Name.Contains("BusinessObjectID") && e.OldValue is int && e.OldValue != e.NewValue ) {
					RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
					BusinessObject bo = repSvc.GetItem<BusinessObject>((int)e.OldValue);
					if ( bo != null ) {
						MemberCreationService memberCreation = GetService(typeof(IMemberCreationService)) as MemberCreationService;
						memberCreation.RemoveProperty(this.FullClassName, bo.Name, null);
						memberCreation.RemoveField(this.FullClassName, bo.Name + "Property");
						string argsNm = bo.Name + Deployment.cExternalDataEventArgs;
						memberCreation.RemoveProperty(this.FullClassName, argsNm, null);
						memberCreation.RemoveField(this.FullClassName, argsNm + "Property");
					}
				}
			} else if ( e.RepositoryItem is Verb && e.Member.Name == "Name" ) {
				Activity[] activities = null;
				IDesignerHost host = (IDesignerHost)this.GetService(typeof(IDesignerHost));
				RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
				if ( host != null && host.RootComponent is CompositeActivity ) {
					activities = GetNestedActivities((CompositeActivity)host.RootComponent);
					foreach ( var item in activities ) {
						LogicalCapabilityActivity lca = item as LogicalCapabilityActivity;
						if ( lca != null ) {
							LogicalActivity la = repSvc.GetItem<LogicalActivity>(lca.LogicalActivityId);
							if ( la != null && la.VerbID == e.RepositoryItem.ID ) {
								lca.Capability = e.NewValue as string;
							}
						}

					}
				}
			} else if ( e.Member.Name.ToLower().Contains("businessobjectid") ) {

			}
		}

		private void initLogicalActivitiesClassProperty(TypeProvider typeProvider)
		{
			CodeMemberProperty prop = Helpers.GetMember<CodeMemberProperty>(
				codeBesideccu, this.FullClassName, "LogicalActivitiesClass");

			while ( prop == null ) {
				_memberCreation.CreateProperty(this.FullClassName,
							   "LogicalActivitiesClass",
							   typeProvider.GetType(this.Namespace + ".LogicalActivities"),
							   null,
							   true,
							   false,
							   false,
							   null,
							   true);
				prop = Helpers.GetMember<CodeMemberProperty>(
					codeBesideccu, this.FullClassName, "LogicalActivitiesClass");
			}
			prop.GetStatements.Clear();

			Type typeLogActs = typeProvider.GetType(this.Namespace + ".LogicalActivities");

			prop.GetStatements.Add(
				new CodeVariableDeclarationStatement(
					typeLogActs,
					"la",
					new CodeCastExpression(
						typeLogActs,
						new CodeMethodInvokeExpression(
							new CodeBaseReferenceExpression(),
							"GetValue",
							new CodeFieldReferenceExpression(
								new CodeTypeReferenceExpression(this.FullClassName),
								"LogicalActivitiesClassProperty")))));
			prop.GetStatements.Add(
				new CodeConditionStatement(
					new CodeBinaryOperatorExpression(
						new CodeVariableReferenceExpression("la"),
						CodeBinaryOperatorType.ValueEquality,
						new CodePrimitiveExpression(null)),
					new CodeAssignStatement(
						new CodeVariableReferenceExpression("la"),
						new CodeObjectCreateExpression(
							typeLogActs,
							new CodeThisReferenceExpression())),
					new CodeExpressionStatement(new CodeMethodInvokeExpression(
						new CodeBaseReferenceExpression(),
						"SetValue",
						new CodeFieldReferenceExpression(
							new CodeTypeReferenceExpression(this.FullClassName),
							"LogicalActivitiesClassProperty"),
						new CodeVariableReferenceExpression("la")))));
			prop.GetStatements.Add(
				new CodeMethodReturnStatement(
					new CodeVariableReferenceExpression("la")));

		}

		/// <summary>
		/// Releases all resources used by the <see cref="T:System.Workflow.ComponentModel.Design.WorkflowDesignerLoader"/>.
		/// </summary>
		public override void Dispose()
		{
			IDesignerLoaderHost host = LoaderHost;
			if ( host != null ) {
				host.RemoveService(typeof(IIdentifierCreationService));
				host.RemoveService(typeof(IMenuCommandService));
				host.RemoveService(typeof(IToolboxService));
				host.RemoveService(typeof(ITypeProvider), true);
				host.RemoveService(typeof(IWorkflowCompilerOptionsService));
				host.RemoveService(typeof(IEventBindingService));
				host.RemoveService(typeof(IWorkflowValidator));
				host.RemoveService(typeof(IMemberCreationService));
				host.RemoveService(typeof(IExtendedUIService));
				IRepositoryChangeService repchange = host.GetService(typeof(IRepositoryChangeService)) as IRepositoryChangeService;
				if ( repchange != null ) {
					repchange.RepositoryChanged -= new RepositoryChangedEventHandler(repchange_RepositoryChanged);
				}
			}

			base.Dispose();
		}

		/// <summary>
		/// When overridden in a derived class, retrieves an object that <see cref="T:System.Workflow.ComponentModel.Design.WorkflowDesignerLoader"/> uses to read from the specified file.
		/// </summary>
		/// <param name="filePath">A string that contains a path to the file to read from.</param>
		/// <returns>
		/// A <see cref="T:System.IO.TextReader"/> to read the specified file.
		/// </returns>
		public override TextReader GetFileReader(string filePath)
		{
			if ( this.tempRulesStream != null )
				return new StringReader(this.tempRulesStream.ToString());
			else
				return null;
		}

		/// <summary>
		/// When overridden in a derived class, gets an object that the <see cref="T:System.Workflow.ComponentModel.Design.WorkflowDesignerLoader"/> uses to write to the specified file.
		/// </summary>
		/// <param name="filePath">A string that contains the path to the file to write to.</param>
		/// <returns>
		/// A <see cref="T:System.IO.TextWriter"/> to write to the file.
		/// </returns>
		public override TextWriter GetFileWriter(string filePath)
		{
			this.tempRulesStream = new StringBuilder();
			return new StringWriter(this.tempRulesStream);
		}

		/// <summary>
		/// When overridden in a derived class, gets the file name of the designer to load.
		/// </summary>
		/// <value></value>
		/// <returns>A string that contains the file name of the designer to load.</returns>
		public override string FileName
		{
			get
			{
				return string.Empty;
			}
		}

		/// <summary>
		/// Note: In case of state machine workflows we need to load the layout from the layout file in the
		/// OnEndLoad method. This is because the layout file is applied to the designer components which are
		/// created in PerformLoad and are available only on the OnEndLoad method
		/// </summary>
		/// <param name="successful">true if load operation is successful; otherwise, false.</param>
		/// <param name="errors">Contains the load errors.</param>
		protected override void OnEndLoad(bool successful, ICollection errors)
		{
			base.OnEndLoad(successful, errors);

			// get used logical activity ids
			_listLogActs = getCurrentLogicalActivityIds();

			//// Load the layout if it exists
			//string layoutFile = Path.Combine(Path.GetDirectoryName(this.xoml), Path.GetFileNameWithoutExtension(this.xoml) + ".layout");
			//if ( File.Exists(layoutFile) ) {
			//    IList loaderrors = null;
			//    using ( XmlReader xmlReader = XmlReader.Create(layoutFile) )
			//        LoadDesignerLayout(xmlReader, out loaderrors);
			//}
		}

		/// <summary>
		/// Load the workflow : This will create the activity tree and its corresponding Designer tree
		/// </summary>
		/// <param name="serializationManager">Class that implements the <see cref="T:System.ComponentModel.Design.Serialization.IDesignerSerializationManager"/> interface, which manages design-time serialization.</param>
		protected override void PerformLoad(IDesignerSerializationManager serializationManager)
		{
			if ( _workflow == null )
				throw new NullReferenceException("Workflow undefined.");

			_listRuleIDs = _workflow.GetRuleIDs();

			base.PerformLoad(serializationManager);
			IDesignerHost designerHost = (IDesignerHost)GetService(typeof(IDesignerHost));

			// get the root activity and add the corresponding object graph to the designer host
			Activity rootActivity = null;
			this.ClassName = _workflow.Name;
			XmlDocument xd = new XmlDocument();
			xd.LoadXml(_workflow.XOML);
			XmlNamespaceManager xnsmgr = new XmlNamespaceManager(xd.NameTable);
			xnsmgr.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
			XmlNode xn = xd.SelectSingleNode("//@x:Class", xnsmgr);
			if ( xn != null ) {
				xn.Value = this.FullClassName;
			}
			_workflow.XOML = xd.DocumentElement.OuterXml;
			using ( StringReader sr = new StringReader(_workflow.XOML) )
			using ( XmlReader reader = new XmlTextReader(sr) ) {
				WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
				rootActivity = xomlSerializer.Deserialize(reader) as Activity;
			}

			if ( rootActivity != null && designerHost != null ) {
				AddObjectGraphToDesignerHost(designerHost, rootActivity);
				Type companionType = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as Type;
				if ( companionType != null )
					SetBaseComponentClassName(companionType.FullName);
			}

			designerHost.Activate();
			// Read from rules file if one exists
			//string rulesFile = Path.Combine(Path.GetDirectoryName(this.xoml), Path.GetFileNameWithoutExtension(this.xoml) + ".rules");
			//if ( File.Exists(rulesFile) ) {
			//    StreamReader rulesReader = new StreamReader(rulesFile);
			//    this.tempRulesStream = new StringBuilder(rulesReader.ReadToEnd());
			//    rulesReader.Close();
			//}
			if ( !string.IsNullOrEmpty(_workflow.Rules) ) {
				this.tempRulesStream = new StringBuilder(_workflow.Rules);
			}
			try {
				generateCode(false);
			} catch ( Exception ex ) {
				ITaskListService taskList = (ITaskListService)this.GetService(typeof(ITaskListService));
				if ( taskList != null ) {
					string msg = string.Format("Workflow '{0}': {1}", _workflow.Name, ex.Message);
					taskList.Add(_workflow, TaskItemType.Error, TaskStatus.None, ex, msg, cTaskListSourceNameGenerate);
				}
			}
		}

		/// <summary>
		/// Writes pending changes to the location that the designer was loaded from.
		/// </summary>
		public override void Flush()
		{
			PerformFlush(null);
		}

		/// <summary>
		/// Save the Xaml file and flush the code compile unit into a .CS file
		/// </summary>
		/// <param name="manager">The manager.</param>
		protected override void PerformFlush(IDesignerSerializationManager manager)
		{
			IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
			ITaskListService taskList = (ITaskListService)this.GetService(typeof(ITaskListService));
			if ( host == null )
				return;

			if ( taskList != null ) taskList.Clear(_workflow, cTaskListSourceNameSave);

			try {
				using ( new WaitMouse() ) {
					Activity rootActivity = host.RootComponent as Activity;
					if ( host != null && host.RootComponent != null ) {

						if ( rootActivity != null ) {
							XmlWriterSettings settings = new XmlWriterSettings();
							settings.Indent = true;
							settings.IndentChars = "\t";
							settings.OmitXmlDeclaration = true;
							settings.ConformanceLevel = ConformanceLevel.Auto;
							settings.NewLineChars = Environment.NewLine;
							settings.NewLineHandling = NewLineHandling.Replace;
							using ( StringWriter sw = new StringWriter() )
							using ( XmlWriter xw = XmlWriter.Create(sw, settings) ) {
								WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
								xomlSerializer.Serialize(xw, rootActivity);
								xw.Flush();
								_workflow.XOML = sw.ToString();
							}
						}
					}

					//string codeBesideFile = Path.Combine(Path.GetDirectoryName(this.xoml), Path.GetFileNameWithoutExtension(this.xoml) + ".cs");

					// Flush CS code
					CSharpCodeProvider provider = new CSharpCodeProvider();
					// Just chooses some formatting options, like four space indenting
					CodeGeneratorOptions options = new CodeGeneratorOptions();
					options.BlankLinesBetweenMembers = true;
					options.BracingStyle = "C";
					options.ElseOnClosing = true;
					options.IndentString = "\t";

					// save CodeBeside
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.CodeBesideCCU, sw, options);
						_workflow.CodeBeside = sw.ToString();
					}
					// save LogicalActivities
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.LogicalActivitiesCCU, sw, options);
						_workflow.CodeLogicalActivity = sw.ToString();
					}
					// save Services
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.ServicesCCU, sw, options);
						_workflow.CodeService = sw.ToString();
					}
					// save Mapping
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.MappingCCU, sw, options);
						_workflow.CodeMapping = sw.ToString();
					}
					// save CodeRules
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.RulesCCU, sw, options);
						_workflow.CodeRules = sw.ToString();
					}
					// save Data
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.DataCCU, sw, options);
						_workflow.CodeData = sw.ToString();
					}
					// save Contracts
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.ContractsCCU, sw, options);
						_workflow.CodeContracts = sw.ToString();
					}
					// save Interface
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.InterfaceCCU, sw, options);
						_workflow.CodeInterface = sw.ToString();
					}
					// save Local Service
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.LocalServiceCCU, sw, options);
						_workflow.CodeLocalService = sw.ToString();
					}
					// save Host Service
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.HostServiceCCU, sw, options);
						_workflow.CodeHosting = sw.ToString();
					}
					// save Orchestration Interface
					using ( StringWriter sw = new StringWriter() ) {
						provider.GenerateCodeFromCompileUnit(this.OrchestrationInterfaceCCU, sw, options);
						_workflow.CodeOrchestrationInterface = sw.ToString();
					}

					// Flush the rules file
					if ( this.tempRulesStream != null ) {
						_workflow.Rules = this.tempRulesStream.ToString();
						//string rulesFile = Path.Combine(Path.GetDirectoryName(this.xoml), Path.GetFileNameWithoutExtension(this.xoml) + ".rules");
						//using ( StreamWriter rulesWriter = new StreamWriter(rulesFile) ) {
						//    rulesWriter.Write(this.tempRulesStream.ToString());
						//}
					} else {
						using ( MemoryStream ms = new MemoryStream() )
						using ( StreamReader sr = new StreamReader(ms) ) {
							XmlSerializer xs = new XmlSerializer(typeof(RuleDefinitions));
							xs.Serialize(ms, new RuleDefinitions());
							ms.Flush();
							ms.Position = 0;
							_workflow.Rules = sr.ReadToEnd();
						}
					}
					// save used rule ids
					_workflow.SetRuleIDs(_listRuleIDs);

					#region State Machine Workflow specific code
					// Need to save the layout in case of State Machine Workflow

					//string layoutFile = Path.Combine(Path.GetDirectoryName(this.xoml), Path.GetFileNameWithoutExtension(this.xoml) + ".layout");
					//ActivityDesigner rootdesigner = host.GetDesigner(rootActivity) as ActivityDesigner;
					//XmlWriter layoutwriter = XmlWriter.Create(layoutFile);
					//IList errors = null;
					//SaveDesignerLayout(layoutwriter, rootdesigner, out errors);
					//layoutwriter.Close();

					#endregion

					// delete logical activites of deleted LogicalCapability/EPActivities
					List<int> lstNewLogActs = getCurrentLogicalActivityIds();
					if ( _listLogActs.Count > 0 ) {
						List<int> lstRemove = new List<int>();
						RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
						if ( repSvc == null )
							throw new NullReferenceException("RepositoryService not available.");
						foreach ( int id in _listLogActs ) {
							if ( !lstNewLogActs.Contains(id) ) {
								IRepositoryItem item = repSvc.GetItem(ItemType.LogicalActivity, id, false);
								if ( item != null && item.ID > 0 ) {
									item.Delete(false);
									lstRemove.Add(item.ID);
								}
							}
						}
						_listLogActs.Clear();
						_listLogActs.AddRange(lstNewLogActs);
					}
					_workflow.ExtendedProperties.LogicalActivityIDs = lstNewLogActs.ToArray();
					BindingListEx<LogicalActivity> _dbLogActs = Global.Data.GetLogicalActivitiesOfWorkflow(_workflow.ID);
					foreach ( LogicalActivity logAct in _dbLogActs ) {
						if ( !lstNewLogActs.Contains(logAct.ID) ) {
							logAct.Delete(false);
						} else {
						}
					}
					_workflow.ExtendedProperties.NamespaceCode = this.Namespace;
				}
			} catch ( Exception ex ) {
				if ( taskList == null ) {
					if ( this.ShowErrorMessageBox ) {
						MessageBox.Show(ex.Message, "Save Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				} else {
					taskList.Add(_workflow, TaskItemType.Error, TaskStatus.None, ex, ex.Message, cTaskListSourceNameSave);
				}
			}
		}
		#endregion

		#region Public Members

		#region Public properties

		/// <summary>
		/// Gets or sets a value indicating whether [show error message box].
		/// </summary>
		/// <value>
		/// 	<c>true</c> if [show error message box]; otherwise, <c>false</c>.
		/// </value>
		public bool ShowErrorMessageBox
		{
			get { return _showErrorMsgs; }
			set { _showErrorMsgs = value; }
		}

		/// <summary>
		/// Gets a value indicating whether [generate data contract].
		/// </summary>
		/// <value>
		/// 	<c>true</c> if [generate data contract]; otherwise, <c>false</c>.
		/// </value>
		public bool GenerateDataContract
		{
			get { return _workflow.GenerateDataContract; }
		}

		/// <summary>
		/// Gets the default namespace.
		/// </summary>
		/// <value>The default namespace.</value>
		public string DefaultNamespace
		{
			get
			{
				return "OpenComposite.Orchestration";
			}
		}

		/// <summary>
		/// Gets or sets the code beside CCU.
		/// </summary>
		/// <value>The code beside CCU.</value>
		public CodeCompileUnit CodeBesideCCU
		{
			get { return codeBesideccu; }
			set { codeBesideccu = value; }
		}
		/// <summary>
		/// Gets or sets the xaml code compile unit.
		/// </summary>
		/// <value>The xaml code compile unit.</value>
		public CodeCompileUnit XamlCodeCompileUnit
		{
			get { return xamlccu; }
			set { xamlccu = value; }
		}
		/// <summary>
		/// Gets or sets the logical activities CCU.
		/// </summary>
		/// <value>The logical activities CCU.</value>
		public CodeCompileUnit LogicalActivitiesCCU
		{
			get { return _codeLogActivities; }
			set { _codeLogActivities = value; }
		}
		/// <summary>
		/// Gets or sets the services CCU.
		/// </summary>
		/// <value>The services CCU.</value>
		public CodeCompileUnit ServicesCCU
		{
			get { return _codeServices; }
			set { _codeServices = value; }
		}
		/// <summary>
		/// Gets or sets the mapping CCU.
		/// </summary>
		/// <value>The mapping CCU.</value>
		public CodeCompileUnit MappingCCU
		{
			get { return _codeMapping; }
			set { _codeMapping = value; }
		}
		/// <summary>
		/// Gets or sets the rules CCU.
		/// </summary>
		/// <value>The rules CCU.</value>
		public CodeCompileUnit RulesCCU
		{
			get { return _codeRules; }
			set { _codeRules = value; }
		}
		/// <summary>
		/// Gets or sets the data CCU.
		/// </summary>
		/// <value>The data CCU.</value>
		public CodeCompileUnit DataCCU
		{
			get { return _codeData; }
			set { _codeData = value; }
		}
		/// <summary>
		/// Gets or sets the contracts CCU.
		/// </summary>
		/// <value>The contracts CCU.</value>
		public CodeCompileUnit ContractsCCU
		{
			get { return _codeContracts; }
			set { _codeContracts = value; }
		}
		/// <summary>
		/// Gets or sets the interface CCU.
		/// </summary>
		/// <value>The interface CCU.</value>
		public CodeCompileUnit InterfaceCCU
		{
			get { return _codeInterface; }
			set { _codeInterface = value; }
		}
		/// <summary>
		/// Gets or sets the local service CCU.
		/// </summary>
		/// <value>The local service CCU.</value>
		public CodeCompileUnit LocalServiceCCU
		{
			get { return _codeLocalService; }
			set { _codeLocalService = value; }
		}
		/// <summary>
		/// Gets or sets the host service CCU.
		/// </summary>
		/// <value>The host service CCU.</value>
		public CodeCompileUnit HostServiceCCU
		{
			get { return _codeHostService; }
			set { _codeHostService = value; }
		}
		/// <summary>
		/// Gets the orchestration interface CCU.
		/// </summary>
		/// <value>The orchestration interface CCU.</value>
		public CodeCompileUnit OrchestrationInterfaceCCU
		{
			get { return _codeWFInterface; }
		}

		/// <summary>
		/// Gets the controller.
		/// </summary>
		/// <value>The controller.</value>
		public WorkflowController Controller
		{
			get { return _controller; }
		}

		/// <summary>
		/// Gets or sets the workflow.
		/// </summary>
		/// <value>The workflow.</value>
		public Repository.Workflow Workflow
		{
			get { return this._workflow; }
			set { this._workflow = value; }
		}
		/// <summary>
		/// Gets or sets the xoml.
		/// </summary>
		/// <value>The xoml.</value>
		public string Xoml
		{
			get
			{
				return this.xoml;
			}
			set
			{
				this.xoml = value;
			}
		}

		/// <summary>
		/// Gets or sets the namespace.
		/// </summary>
		/// <value>The namespace.</value>
		public string Namespace
		{
			get
			{
				if ( _workflow != null ) {
					return string.Format("{0}.{1}", this.DefaultNamespace, _workflow.Name);
				} else {
					return this.DefaultNamespace;
				}
			}
			set { if ( _workflow != null ) _workflow.ExtendedProperties.NamespaceCode = value; }
		}
		/// <summary>
		/// Gets the namespace data.
		/// </summary>
		/// <value>The namespace data.</value>
		public string NamespaceData
		{
			get { return string.Format("{0}.{1}", this.Namespace, "Data"); }
		}
		/// <summary>
		/// Gets the namespace rules.
		/// </summary>
		/// <value>The namespace rules.</value>
		public string NamespaceRules
		{
			get { return "OpenComposite.Orchestration"; }
		}

		/// <summary>
		/// Gets or sets the name of the class.
		/// </summary>
		/// <value>The name of the class.</value>
		public string ClassName
		{
			get { return _workflow != null ? _workflow.Name : "Orchestration1"; }
			set { if ( _workflow != null ) _workflow.Name = value; }
		}
		/// <summary>
		/// Gets the full name of the class.
		/// </summary>
		/// <value>The full name of the class.</value>
		public string FullClassName
		{
			get
			{
				if ( string.IsNullOrEmpty(this.Namespace) )
					return this.ClassName;
				else
					return string.Format("{0}.{1}", this.Namespace, this.ClassName);
			}
		}
		/// <summary>
		/// Gets the name of the interface.
		/// </summary>
		/// <value>The name of the interface.</value>
		public string InterfaceName
		{
			get { return "I" + this.ClassName; }
		}
		/// <summary>
		/// Gets the name of the callback interface.
		/// </summary>
		/// <value>The name of the callback interface.</value>
		public string CallbackInterfaceName
		{
			get { return "I" + this.ClassName + "Callback"; }
		}
		/// <summary>
		/// Gets the name of the orchestration interface.
		/// </summary>
		/// <value>The name of the orchestration interface.</value>
		public string OrchestrationInterfaceName
		{
			get { return "I" + this.ClassName + "Orchestration"; }
		}

		/// <summary>
		/// Gets the full name of the external data exchange interface.
		/// </summary>
		/// <value>The full name of the external data exchange interface.</value>
		public string ExternalDataExchangeInterfaceFullName
		{
			get { return this.Namespace + "." + _ctdLocalInterface.Name; }
		}
		/// <summary>
		/// Gets the type of the external data exchange interface.
		/// </summary>
		/// <value>The type of the external data exchange interface.</value>
		public Type ExternalDataExchangeInterfaceType
		{
			get
			{
				TypeProvider typeProvider = GetService(typeof(ITypeProvider)) as TypeProvider;
				return typeProvider.GetType(this.ExternalDataExchangeInterfaceFullName);
			}
		}

		/// <summary>
		/// Gets the rule IDs.
		/// </summary>
		/// <value>The list of rule IDs.</value>
		public List<int> RuleIDs
		{
			get { return _listRuleIDs; }
		}
		/// <summary>
		/// Gets the logical activity IDs.
		/// </summary>
		/// <value>The list of logical activity IDs.</value>
		public List<int> LogActIDs
		{
			get { return _listLogActs; }
		}

		#endregion

		#region Methods

		/// <summary>
		/// Generates the specified simple generate.
		/// </summary>
		/// <param name="simpleGenerate">if set to <c>true</c> [simple generate].</param>
		public void Generate(bool simpleGenerate)
		{
			generateCode(simpleGenerate);
		}

		/// <summary>
		/// Creates the orchestration interface.
		/// </summary>
		/// <param name="deployment">The deployment.</param>
		/// <param name="op">The op.</param>
		/// <param name="typeRefInput">The type ref input.</param>
		/// <param name="typeRefOutput">The type ref output.</param>
		/// <param name="method">The method.</param>
		//public void CreateOrchestrationInterface(
		//    Deployment deployment,
		//    out Repository.Operation op, out CodeTypeReference typeRefInput,
		//    out CodeTypeReference typeRefOutput, out CodeMemberMethod method)
		//{
		//    op = null;
		//    typeRefInput = null;
		//    typeRefOutput = null;
		//    method = null;
		//    TypeProvider typeProvider = (TypeProvider)GetService(typeof(ITypeProvider));

		//    if ( this.Workflow.BuildType != WorkflowBuildType.WCF_WindowsForm ) {

		//        op = null;
		//        SearchableSortableBindingList<Repository.Operation> ops = Global.Data.GetWorkflowOperation(_workflow.ID);
		//        if ( ops.Count > 0 ) {
		//            op = ops[0];
		//        }

		//        ///////////////////////////
		//        #region START generate Data classes
		//        if ( op != null ) {
		//            XmlSchemaSet xsdset = deployment.createXmlSchemaSetForDataContract();
		//            if ( op.InputSchema != null ) {
		//                xsdset.Add(op.InputSchema);
		//            }
		//            if ( op.OutputSchema != null && op.OutputSchemaString != op.InputSchemaString ) {
		//                xsdset.Add(op.OutputSchema);
		//            }
		//            xsdset.Compile();
		//            if ( this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS ) {
		//                deployment.addXmlClassesToDataCode(this.DataCCU, this.NamespaceData, xsdset);
		//            } else { // if ( this.Workflow.BuildType == WorkflowBuildType.WCF_IIS )
		//                deployment.addDataContractsToDataCode(this.DataCCU, this.NamespaceData, xsdset);
		//            }
		//            // refresh typeProvider
		//            refreshTypeProvider(ref typeProvider, ref _codeData);
		//        } else if ( this.Workflow.InputBusinessObjectID > 0 || this.Workflow.OutputBusinessObjectID > 0 ) {
		//            XmlSchemaSet xsdset = deployment.createXmlSchemaSetForDataContract();
		//            if ( this.Workflow.InputBusinessObject != null && this.Workflow.InputBusinessObject.Schema != null )
		//                xsdset.Add(this.Workflow.InputBusinessObject.Schema);
		//            if ( this.Workflow.OutputBusinessObject != null &&
		//                 this.Workflow.OutputBusinessObject.Schema != null &&
		//                 this.Workflow.OutputBusinessObjectID != this.Workflow.InputBusinessObjectID )
		//                xsdset.Add(this.Workflow.OutputBusinessObject.Schema);
		//            xsdset.Compile();
		//            if ( this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS ) {
		//                deployment.addXmlClassesToDataCode(this.DataCCU, this.NamespaceData, xsdset);
		//            } else { // if ( this.Workflow.BuildType == WorkflowBuildType.WCF_IIS )
		//                deployment.addDataContractsToDataCode(this.DataCCU, this.NamespaceData, xsdset);
		//            }
		//            // refresh typeProvider
		//            refreshTypeProvider(ref typeProvider, ref _codeData);
		//        }
		//        #endregion END generate Data classes
		//        ///////////////////////////
		//        typeRefOutput = null;
		//        typeRefInput = null;
		//        if ( op != null ) {
		//            getGeneratedIOTypesOfOperation(typeProvider, op, out typeRefOutput, out typeRefInput);
		//            // add property for output business object to code beside
		//            if ( typeRefInput != null ) {
		//                addPropertyForBObjectToCodeBeside(typeProvider, op.GetInputBusinessObject(), typeRefInput);
		//                _workflow.ExtendedProperties.InputType = typeRefInput.BaseType;
		//            }
		//            if ( typeRefOutput != null ) {
		//                addPropertyForBObjectToCodeBeside(typeProvider, op.GetOutputBusinessObject(), typeRefOutput);
		//                _workflow.ExtendedProperties.OutputType = typeRefOutput.BaseType;
		//            }
		//        } else {
		//            getGeneratedIOTypesOfWorkflow(typeProvider, this.Workflow, out typeRefOutput, out typeRefInput);
		//            // add property for output business object to code beside
		//            if ( typeRefInput != null ) {
		//                addPropertyForBObjectToCodeBeside(typeProvider, this.Workflow.InputBusinessObject, typeRefInput);
		//                _workflow.ExtendedProperties.InputType = typeRefInput.BaseType;
		//            }
		//            if ( typeRefOutput != null ) {
		//                addPropertyForBObjectToCodeBeside(typeProvider, this.Workflow.OutputBusinessObject, typeRefOutput);
		//                _workflow.ExtendedProperties.OutputType = typeRefOutput.BaseType;
		//            }
		//        }
		//        ///////////////////////////
		//        #region START generate Interface
		//        method = null;
		//        string opname = "";
		//        if ( op != null ) {
		//            opname = op.Name;
		//        } else {
		//            opname = this.Workflow.StartName;
		//        }
		//        if ( !string.IsNullOrEmpty(opname) ) {
		//            foreach ( CodeTypeMember member in _ctdInterface.Members ) {
		//                if ( member is CodeMemberMethod && member.Name == opname ) {
		//                    method = (CodeMemberMethod)member;
		//                    break;
		//                }
		//            }
		//            if ( method == null ) {
		//                method = new CodeMemberMethod();
		//                method.Name = opname;
		//                method.Attributes = MemberAttributes.Public;
		//                if ( typeRefInput != null )
		//                    method.Parameters.Add(
		//                        new CodeParameterDeclarationExpression(typeRefInput, "input"));

		//                if ( this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS ) {
		//                    // if ASMX
		//                    if ( typeRefOutput != null ) {
		//                        method.ReturnType = typeRefOutput;
		//                    }
		//                } else {
		//                    // if WCF
		//                    if ( typeRefOutput != null ) {
		//                        method.ReturnType = typeRefOutput;
		//                        method.CustomAttributes.Add(
		//                            new CodeAttributeDeclaration(
		//                                new CodeTypeReference(typeof(OperationContractAttribute))));
		//                    } else {
		//                        method.CustomAttributes.Add(
		//                            new CodeAttributeDeclaration(
		//                                new CodeTypeReference(typeof(OperationContractAttribute)),
		//                                new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true))));
		//                    }

		//                    //if ( typeRefOutput != null ) {
		//                    //    // create and add callback method to callback interface
		//                    //    CodeMemberMethod methodCallback = new CodeMemberMethod();
		//                    //    methodCallback.Name = opname + "Callback";
		//                    //    methodCallback.Attributes = MemberAttributes.Public;
		//                    //    methodCallback.CustomAttributes.Add(
		//                    //        new CodeAttributeDeclaration(
		//                    //            new CodeTypeReference(typeof(OperationContractAttribute)),
		//                    //            new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true))));
		//                    //    methodCallback.Parameters.Add(
		//                    //        new CodeParameterDeclarationExpression(typeRefOutput, "output"));

		//                    //    _ctdInterfaceCallback.Members.Add(methodCallback);
		//                    //}
		//                }
		//                _ctdInterface.Members.Add(method);
		//                _workflow.ExtendedProperties.StartMethodName = method.Name;
		//            }
		//            refreshTypeProvider(ref typeProvider, ref _codeInterface);
		//        }
		//        _workflow.ExtendedProperties.InterfaceName = _ctdInterface.Name;
		//        #endregion END generate Interface
		//        ///////////////////////////
		//    }
		//    ///////////////////////////
		//    #region START add properties for simulation environment
		//    addSimulationPropertiesToWFCodeBeside();
		//    #endregion END add properties for simulation environment
		//    ///////////////////////////

		//}

		private void addSimulationPropertiesToWFCodeBeside()
		{
			_memberCreation.CreateProperty(this.FullClassName,
										   PropertyNames.IsSimulation,
										   typeof(bool),
										   null,
										   true,
										   false,
										   false,
										   null,
										   false);
			_memberCreation.CreateProperty(this.FullClassName,
											PropertyNames.IsDocumentFlowSimulation,
											typeof(bool),
											null,
											true,
											false,
											false,
											null,
											false);
			_memberCreation.CreateProperty(this.FullClassName,
										   PropertyNames.SimulateAllLogicalActivities,
										   typeof(bool),
										   null,
										   true,
										   false,
										   false,
										   null,
										   false);
		}
		/// <summary>
		/// Sets the start and end activities.
		/// </summary>
		/// <param name="op">The op.</param>
		/// <param name="typeRefInput">The type ref input.</param>
		/// <param name="typeRefOutput">The type ref output.</param>
		/// <param name="method">The method.</param>
		//public void SetStartEndActivities(Repository.Operation op,
		//    CodeTypeReference typeRefInput, CodeTypeReference typeRefOutput,
		//    CodeMemberMethod method)
		//{
		//    TypeProvider typeProvider = (TypeProvider)GetService(typeof(ITypeProvider));
		//    ///////////////////////////
		//    // START create workflow input / output activites
		//    if ( this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS ) {
		//        setASMXStartEnd(typeProvider, op, typeRefOutput, typeRefInput, method);
		//    } else if ( this.Workflow.BuildType == WorkflowBuildType.WCF_IIS ) {
		//        setWCFStartEnd(typeProvider, op, typeRefOutput, typeRefInput, method);
		//    }
		//    // END create workflow input / output activites
		//    ///////////////////////////
		//}

		/// <summary>
		/// Adds the start and end activities.
		/// </summary>
		/// <param name="weStart">The we start.</param>
		/// <param name="wmReply">The wm reply.</param>
		public void AddStartEndActivities(WorkflowEvent weStart, WorkflowMethod wmReply)
		{
			//if ( string.IsNullOrEmpty(_workflow.StartName) ) return;

			IDesignerHost host = (IDesignerHost)this.GetService(typeof(IDesignerHost));
			RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			TypeProvider typeProvider = GetService(typeof(ITypeProvider)) as TypeProvider;
			Deployment deployment = new Deployment(host);

			CompositeActivity composite;
			if ( _workflow.Type == WorkflowType.Business_Process ) {
				composite = host.RootComponent as HorizontalWorkflowActivity;
			} else {
				composite = host.RootComponent as SequentialWorkflowActivity;
			}
			int i;
			string nameStart = _workflow.StartName;
			string nameReply = _workflow.StartName + Deployment.c_Reply;
			LogicalInputActivity activityStart = null;
			LogicalMethodCallActivity activityReply = null;
			if ( composite.Activities.Count > 0 ) {
				activityStart = composite.Activities[0] as LogicalInputActivity;
				activityReply = composite.Activities[composite.Activities.Count - 1] as LogicalMethodCallActivity;
			}
			//searchStartEnd(composite, nameStart, nameReply, out activityStart, out activityReply);

			DesignerTransaction trans = host.CreateTransaction("Create Start/Reply Activities.");
			try {
				generateProxyForWCFService(deployment);
				if ( composite.Activities.Remove(activityStart) ) {
					host.DestroyComponent(activityStart);
					activityStart = null;
				}
				if ( composite.Activities.Remove(activityReply) ) {
					host.DestroyComponent(activityReply);
					activityReply = null;
				}
				i = 0;
				while ( host.Container.Components[nameStart] != null ) {
					nameStart = _workflow.StartName + ( ( ++i ).ToString() );
				}
				if ( activityStart == null ) {
					LogicalActivity la = weStart.AssignLogicalActivity(-1);
					activityStart = host.CreateComponent(typeof(LogicalInputActivity), nameStart)
								as LogicalInputActivity;
					activityStart.Name = nameStart;
					activityStart.LogicalActivityId = la.ID;
					activityStart.LogicalActivityName = la.Name;
					activityStart.Text = _workflow.StartName;
					activityStart.HasOutputObject = la.HasOutputBusinessObject;
					if ( composite is HorizontalWorkflowActivity ) {
						CompositeActivity ca1 = composite.Activities[0] as CompositeActivity;
						if ( ca1 != null ) {
							ca1.Activities.Insert(0, activityStart);
						}
					} else {
						composite.Activities.Insert(0, activityStart);
					}
					initLogicalInputActivity(host, repSvc, typeProvider, activityStart, deployment);
					if ( la.HasOutputBusinessObject ) {
						activityStart.SetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty,
							string.Format("{0}_{1}", nameStart, la.OutputBusinessObject.Name));
					}
				} else {
					// rename
					activityStart.Name = nameStart;
					activityStart.Text = _workflow.StartName;
				}
				i = 0;
				while ( host.Container.Components[nameReply] != null ) {
					nameReply = _workflow.StartName + Deployment.c_Reply + ( ( ++i ).ToString() );
				}
				if ( activityReply == null && _workflow.OutputBusinessObjectID > 0 && wmReply != null ) {
					LogicalActivity la = wmReply.AssignLogicalActivity(-1);
					activityReply = host.CreateComponent(typeof(LogicalMethodCallActivity), nameReply)
								as LogicalMethodCallActivity;
					activityReply.Name = nameReply;
					activityReply.LogicalActivityId = la.ID;
					activityReply.LogicalActivityName = la.Name;
					activityReply.Text = _workflow.StartName + Environment.NewLine + "Reply";
					if ( composite is HorizontalWorkflowActivity ) {
						CompositeActivity ca1 = composite.Activities[composite.Activities.Count - 1] as CompositeActivity;
						if ( ca1 != null ) {
							ca1.Activities.Add(activityReply);
						}
					} else {
						composite.Activities.Add(activityReply);
					}
					initLogicalMethodCallActivity(host, repSvc, typeProvider, activityReply, deployment);
				} else {
					// rename
					activityStart.Name = nameReply;
					activityStart.Text = _workflow.StartName;
				}
				trans.Commit();
			} catch ( Exception ex ) {
				Trace.WriteLine(ex.Message);
				trans.Cancel();
			}
			RefreshAllCode();
		}
		private void searchStartEnd(
			CompositeActivity composite,
			string nameStartEvent, string nameReplyMethod,
			out LogicalInputActivity startActivity, out LogicalMethodCallActivity replyActivity)
		{
			startActivity = composite.Activities.Find(
				delegate(Activity a)
				{
					LogicalInputActivity act = a as LogicalInputActivity;
					return ( act != null && act.EventName == nameStartEvent );
				}) as LogicalInputActivity;
			replyActivity = composite.Activities.Find(
				delegate(Activity a)
				{
					LogicalMethodCallActivity act = a as LogicalMethodCallActivity;
					return ( act != null && act.MethodName == nameReplyMethod );
				}) as LogicalMethodCallActivity;
		}

		/// <summary>
		/// Saves the workflow files.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <returns></returns>
		public List<string> SaveFiles(string path)
		{
			List<string> files = new List<string>();

			writeStringToFile(Path.Combine(path, "Contracts.cs"), _workflow.CodeContracts);
			writeStringToFile(Path.Combine(path, "Data.cs"), _workflow.CodeData);
			writeStringToFile(Path.Combine(path, "IOrchestration.cs"), _workflow.CodeInterface);
			writeStringToFile(Path.Combine(path, "LogicalActivities.cs"), _workflow.CodeLogicalActivity);
			writeStringToFile(Path.Combine(path, "Mapping.cs"), _workflow.CodeMapping);
			writeStringToFile(Path.Combine(path, "Orchestration1.xoml"), _workflow.XOML);
			writeStringToFile(Path.Combine(path, "Orchestration1.xoml.cs"), _workflow.CodeBeside);
			writeStringToFile(Path.Combine(path, "Orchestration1.rules"), _workflow.Rules);
			writeStringToFile(Path.Combine(path, "Rules.cs"), _workflow.CodeRules);
			writeStringToFile(Path.Combine(path, "ServiceCalls.cs"), _workflow.CodeService);
			writeStringToFile(Path.Combine(path, "LocalService.cs"), _workflow.CodeLocalService);
			writeStringToFile(Path.Combine(path, "IWFInterface.cs"), _workflow.CodeOrchestrationInterface);

			// TODO: Remove if statement then enterprise mashups completed
			if ( _workflow.BuildType != WorkflowBuildType.WCF_WindowsForm ) {
				writeStringToFile(Path.Combine(path, "Service.cs"), _workflow.CodeHosting);
			}
			string configPath = Path.Combine(path, "app.config");
			if ( _configuration.FilePath == configPath ) {
				_configuration.Save(ConfigurationSaveMode.Minimal, true);
			} else {
				_configuration.SaveAs(configPath, ConfigurationSaveMode.Minimal, true);
			}

			files.Add(Path.Combine(path, "Contracts.cs"));
			files.Add(Path.Combine(path, "Data.cs"));
			files.Add(Path.Combine(path, "IOrchestration.cs"));
			files.Add(Path.Combine(path, "LogicalActivities.cs"));
			files.Add(Path.Combine(path, "Mapping.cs"));
			files.Add(Path.Combine(path, "Orchestration1.xoml"));
			files.Add(Path.Combine(path, "Orchestration1.xoml.cs"));
			files.Add(Path.Combine(path, "Orchestration1.rules"));
			files.Add(Path.Combine(path, "Rules.cs"));
			files.Add(Path.Combine(path, "ServiceCalls.cs"));
			files.Add(Path.Combine(path, "LocalService.cs"));
			files.Add(Path.Combine(path, "IWFInterface.cs"));
			// TODO: Remove if statement then enterprise mashups completed
			if ( _workflow.BuildType != WorkflowBuildType.WCF_WindowsForm ) {
				files.Add(Path.Combine(path, "Service.cs"));
			}

			return files;
		}
		/// <summary>
		/// Deletes the workflow files.
		/// </summary>
		/// <param name="path">The path.</param>
		public void DeleteFiles(string path)
		{
			File.Delete(Path.Combine(path, "Contracts.cs"));
			File.Delete(Path.Combine(path, "Data.cs"));
			File.Delete(Path.Combine(path, "IOrchestration.cs"));
			File.Delete(Path.Combine(path, "LogicalActivities.cs"));
			File.Delete(Path.Combine(path, "Mapping.cs"));
			File.Delete(Path.Combine(path, "Orchestration1.xoml"));
			File.Delete(Path.Combine(path, "Orchestration1.xoml.cs"));
			File.Delete(Path.Combine(path, "Orchestration1.rules"));
			File.Delete(Path.Combine(path, "Rules.cs"));
			File.Delete(Path.Combine(path, "ServiceCalls.cs"));
			File.Delete(Path.Combine(path, "LocalService.cs"));
			File.Delete(Path.Combine(path, "Service.cs"));
			File.Delete(Path.Combine(path, "app.config"));
		}

		/// <summary>
		/// Refreshes all code.
		/// </summary>
		public void RefreshAllCode()
		{
			TypeProvider typeProvider = GetService(typeof(ITypeProvider)) as TypeProvider;
			refreshTypeProvider(ref typeProvider, ref _codeContracts);
			refreshTypeProvider(ref typeProvider, ref _codeData);
			refreshTypeProvider(ref typeProvider, ref _codeLogActivities);
			refreshTypeProvider(ref typeProvider, ref _codeMapping);
			refreshTypeProvider(ref typeProvider, ref _codeRules);
			refreshTypeProvider(ref typeProvider, ref _codeServices);
			refreshTypeProvider(ref typeProvider, ref _codeInterface);
			refreshTypeProvider(ref typeProvider, ref _codeLocalService);
		}

		/// <summary>
		/// Adds the business rule to code.
		/// </summary>
		/// <param name="brule">The business rule.</param>
		public void AddRuleToCode(RepositoryBusinessRule brule)
		{
			Deployment deploy = new Deployment(this.LoaderHost);
			deploy.AddRuleToCodeCompileUnit(brule, this.RulesCCU, this.Workflow, _listRuleIDs, _listRuleConstIDs);
		}
		#endregion

		#endregion

		#region Private Members

		#region Constants
		private const string cTaskListSourceNameGenerate = "Generate Workflow";
		private const string cTaskListSourceNameSave = "Save Workflow";
		#endregion

		#region Variables

		private Repository.Workflow _workflow;
		private WorkflowController _controller;
		private List<int> _listRuleIDs;
		private List<int> _listLogActs;
		private List<int> _listRuleConstIDs;

		private Configuration _configuration;

		private bool _showErrorMsgs;

		//private string _wfNamespaceName = "OpenComposite.Orchestration";
		//private string _wfName = "Orchestration1";
		//private string _wfClassName = "";

		private string xoml = string.Empty;
		private StringBuilder tempRulesStream = null;

		// we maintain two code compile units: 1 for code beside file and 1 for xaml file
		private CodeCompileUnit codeBesideccu = null;
		private CodeTypeDeclaration _ctdBeside = null;
		private CodeMemberMethod _methodBesideInit = null;
		private CodeMemberField _fieldBesideMapping = null;
		private CodeMemberField _fieldBesideRules = null;
		private CodeMemberProperty _propBesideMapping = null;
		private CodeMemberProperty _propBesideRules = null;

		private CodeCompileUnit xamlccu;

		// addional code compile units for special classes

		private CodeCompileUnit _codeLogActivities;
		private CodeTypeDeclaration _ctdLogActs;

		private CodeCompileUnit _codeServices;
		private CodeTypeDeclaration _ctdServices;

		private CodeCompileUnit _codeMapping;
		private CodeTypeDeclaration _ctdMapping;
		private CodeConstructor _ctorMapping;

		private CodeCompileUnit _codeRules;
		private CodeTypeDeclaration _ctdRules;

		private CodeCompileUnit _codeData;
		private CodeCompileUnit _codeContracts;

		private CodeCompileUnit _codeInterface;
		private CodeTypeDeclaration _ctdInterface;
		private CodeTypeDeclaration _ctdInterfaceCallback;

		private CodeCompileUnit _codeLocalService;
		private CodeNamespace _nsLocalService;
		private CodeTypeDeclaration _ctdLocalService;
		private CodeTypeDeclaration _ctdLocalInterface;

		private CodeCompileUnit _codeHostService;
		private CodeTypeDeclaration _ctdHostService;

		private CodeCompileUnit _codeWFInterface;
		private CodeTypeDeclaration _ctdWFInterface;

		private MemberCreationService _memberCreation;

		#endregion

		#region Methods

		private void generateCode(bool simpleGenerate)
		{
			IDesignerHost host = (IDesignerHost)this.GetService(typeof(IDesignerHost));

			//WorkflowCodeGenerator gen = new WorkflowCodeGenerator(_workflow, _listRuleIDs, _listRuleConstIDs, host);
			//gen.GenerateCode();

			#region TIMER
#if TIMER
			DateTime dtStart = DateTime.Now;
			Debug.WriteLine("simpleGenerate = " + simpleGenerate.ToString());
			Debug.WriteLine("Start: " + dtStart.ToString("HH:mm:ss.ffffff"));
#endif
			#endregion

			#region get services
			RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			ITaskListService taskList = (ITaskListService)this.GetService(typeof(ITaskListService));
			if ( repSvc == null ) throw new NullReferenceException("Repository Service missing.");
			#endregion

			#region initialize code generation
			Deployment deployment = new Deployment(host);
			WaitMouse wait = new WaitMouse();
			DesignerTransaction trans = null;
			if ( host != null ) trans = host.CreateTransaction();

			object selectedItem = getSelectedItem();
			setSelectedItem(null);

			if ( taskList != null ) taskList.Clear(_workflow, cTaskListSourceNameGenerate);

			Dictionary<int, string> dicWebServiceIDEPConfigName = new Dictionary<int, string>();
			#endregion

			try {

				#region initialize workflow and compile units
				this.ClassName = _workflow.Name;
				_workflow.ExtendedProperties.FullName = this.FullClassName;
				SetBaseComponentClassName(this.FullClassName);
				Activity main;
				if ( _workflow.Type == WorkflowType.Business_Process ||
					 _workflow.Type == WorkflowType.Mashup_Horizontal ) {
					main = host.RootComponent as HorizontalWorkflowActivity;
					this.CodeBesideCCU.Namespaces[0].Types[0].BaseTypes.Clear();
					this.CodeBesideCCU.Namespaces[0].Types[0].BaseTypes.Add(typeof(HorizontalWorkflowActivity));
				} else {
					main = host.RootComponent as SequentialWorkflowActivity;
					this.CodeBesideCCU.Namespaces[0].Types[0].BaseTypes.Clear();
					this.CodeBesideCCU.Namespaces[0].Types[0].BaseTypes.Add(typeof(SequentialWorkflowActivity));
				}
				this.CodeBesideCCU.Namespaces[0].Types[0].BaseTypes.Add(this.OrchestrationInterfaceName);

				main.Name = _workflow.Name;
				main.SetValue(WorkflowMarkupSerializer.XClassProperty, this.FullClassName);
				ServiceGenerationType currentSvcGenType;
				TypeProvider typeProvider = GetService(typeof(ITypeProvider)) as TypeProvider;
				MemberCreationService memberCreation = GetService(typeof(IMemberCreationService)) as MemberCreationService;
				if ( typeProvider == null )
					throw new NullReferenceException("TypeProvider missing.");
				if ( memberCreation == null )
					throw new NullReferenceException("MemberCreationService missing.");

				initCompileUnits(simpleGenerate);
				RefreshAllCode();

				// save Workflow Informations
				_workflow.ExtendedProperties.NamespaceCode = this.Namespace;
				_workflow.ExtendedProperties.FullName = this.FullClassName;
				_workflow.ExtendedProperties.InterfaceName = this.InterfaceName;
				_workflow.ExtendedProperties.NamespaceBase = this.DefaultNamespace;
				#endregion

				#region initialize config file
				if ( !simpleGenerate ) {
					string pathTmp = Path.Combine(Path.Combine(Path.GetTempPath(), "OpenComposite"), this.ClassName);
					if ( !Directory.Exists(pathTmp) ) Directory.CreateDirectory(pathTmp);
					string configFile = Path.Combine(pathTmp, "app.config");
					if ( File.Exists(configFile) ) {
						File.Delete(configFile);
					}
					Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration();
					ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
					fileMap.ExeConfigFilename = configFile;
					fileMap.MachineConfigFilename = machineConfig.FilePath;

					_configuration = ConfigurationManager
						.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
					_configuration.NamespaceDeclared = true;
					_configuration.Save(ConfigurationSaveMode.Minimal, true);
				}
				#endregion

				#region initialize simulation
				addSimulationPropertiesToWFCodeBeside();
				#endregion

				#region generate mashup form
				if ( !simpleGenerate ) {
					if ( _workflow.Type == WorkflowType.Mashup ||
						 _workflow.Type == WorkflowType.Mashup_Horizontal ) {
						generateMashupForm();
					}
				}
				#endregion

				#region add rules
				int[] ruleids = _listRuleIDs.ToArray();
				foreach ( int id in ruleids ) {
					Repository.RepositoryBusinessRule brule = null;
					try {
						brule = repSvc.GetItem(ItemType.BRule, id, true) as Repository.RepositoryBusinessRule;
					} catch ( RepositoryItemDeletedException ) {
						_listRuleIDs.Remove(id);
						continue;
					}
					if ( brule != null ) {
						foreach ( int ruleid in brule.GetUsedBusinessRuleIDs() ) {
							if ( !_listRuleIDs.Contains(ruleid) ) {
								Repository.RepositoryBusinessRule rule = null;
								try {
									rule = repSvc.GetItem(ItemType.BRule, ruleid, true) as Repository.RepositoryBusinessRule;
								} catch ( RepositoryItemDeletedException ) {
									continue;
								}
								if ( rule != null ) {
									AddRuleToCode(rule);
								}
							}
						}
						List<int> usedconsts = brule.GetUsedRuleConstantIDs();
						if ( usedconsts != null ) {
							foreach ( int constid in usedconsts ) {
								if ( !_listRuleConstIDs.Contains(constid) )
									_listRuleConstIDs.Add(constid);
							}
						}
						AddRuleToCode(brule);

						if ( brule.ExtendedProperties.RuleType ==
								RepositoryBusinessRule.BusinessRuleType.GenericRule ) {
							#region update rule methods call
							CodeMethodInvokeExpression methinvoke =
								deployment.GetBusinessRuleInvokeExpression(
									this.RulesCCU, new CodeThisReferenceExpression(),
									brule, this.NamespaceRules);
							RuleDefinitions ruleDef = getRuleDefinitions();
							if ( ruleDef != null ) {
								foreach ( RuleCondition rulecond in ruleDef.Conditions ) {
									foreach ( var result in brule.Results.Split(';') ) {
										RuleExpressionCondition ruleexp = rulecond as RuleExpressionCondition;
										if ( ruleexp != null && ruleexp.Name == ( brule.Name + "_" + result ) ) {
											CodeBinaryOperatorExpression binopexpr =
												ruleexp.Expression as CodeBinaryOperatorExpression;
											binopexpr.Left = methinvoke;
											setRuleDefinitions(ruleDef);
											if ( host != null && host.RootComponent is CompositeActivity ) {
												( (CompositeActivity)host.RootComponent )
													.SetValue(RuleDefinitions.RuleDefinitionsProperty, ruleDef);
											}
											break;
										}
									}
								}
							}
							#endregion
						}
					}
				}
				// IF ConfigurationLevel == UtilizeConfiguration THEN create constructor
				generateRuleConstantsCode(repSvc);

				refreshTypeProvider(ref typeProvider, ref _codeRules);

				#endregion

				#region initialize process variables
				addProcessVariablesToCodeBeside(deployment);
				#endregion

				#region initalize activity correlation
				//foreach ( Repository.Workflow.CorrelationId cid in Workflow.ExtendedProperties.CorrelationIds ) {
				//    CodeMemberField field = new CodeMemberField(typeof(string), cid.Name);
				//    field.InitExpression = new CodePrimitiveExpression(cid.Id);
				//    _ctdServices.Members.Add(field);
				//}
				#endregion
				#region get all activities
				Activity[] activities = null;
				if ( host != null && host.RootComponent is CompositeActivity ) {
					activities = GetNestedActivities((CompositeActivity)host.RootComponent);
				} else {
					activities = GetNestedActivities(Helpers.GetRootActivity(_workflow) as CompositeActivity);
				}
				if ( activities == null ) {
					throw new Exception("No Activities available.");
				}

				// refresh activities
				foreach ( Activity act in activities ) {
					if ( act is LogicalCapabilityActivity ) {
						bool oldValue = (bool)act.GetValue(LogicalCapabilityActivity.HasOutputObjectProperty);
						int logActId = (int)act.GetValue(LogicalCapabilityActivity.LogicalActivityIdProperty);
						LogicalActivity logAct = Global.Data.RepositoryService.GetItem<LogicalActivity>(logActId);
						if ( logAct == null ) continue;
						bool newValue = logAct.HasOutputBusinessObject;
						if ( oldValue != newValue ) {
							TypeDescriptor.GetProperties(act)["HasOutputObject"].SetValue(act, newValue);
						}
					}
					if ( act is LogicalCapabilityActivity ) {
						object oldValue = act.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty);
						int logActId = (int)act.GetValue(LogicalCapabilityActivity.LogicalActivityIdProperty);
						LogicalActivity logAct = Global.Data.RepositoryService.GetItem<LogicalActivity>(logActId);

						if ( logAct == null || !logAct.HasOutputBusinessObject ) continue;
						if ( oldValue == null ) {
							act.SetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty,
								string.Format("{0}_{1}", act.Name, logAct.OutputBusinessObject.Name));
						}
					} else if ( act is DataAggregatorActivity ) {
						object oldValue = act.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty);
						int logActId = (int)act.GetValue(LogicalCapabilityActivity.LogicalActivityIdProperty);
						LogicalActivity logAct = Global.Data.RepositoryService.GetItem<LogicalActivity>(logActId);

						if ( logAct == null || !logAct.HasOutputBusinessObject ) continue;
						if ( oldValue == null ) {
							act.SetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty,
								string.Format("{0}_{1}", act.Name, logAct.OutputBusinessObject.Name));
						}
					}
				}
				#endregion

				#region initialize code snippets
				// remove deleted code snippets
				try {
					List<Repository.Workflow.MethodCodeSnippet> methods = _workflow.ExtendedProperties.MethodCodeSnippets;

					for ( int i = methods.Count - 1; i >= 0; i-- ) {
						Repository.Workflow.MethodCodeSnippet method = methods[i];
						if ( string.IsNullOrEmpty(method.ActivityName) ) {
							CodeMemberMethod meth = deployment.getMethodFromCode(this.CodeBesideCCU, this.FullClassName, method.MethodName);
							if ( meth != null ) {
								if ( codeBesideccu.Namespaces.Count > 0 && codeBesideccu.Namespaces[0].Types.Count > 0 ) {
									codeBesideccu.Namespaces[0].Types[0].Members.Remove(meth);
								}
							}
							methods.Remove(method);
							continue;
						} else {
							bool found = false;
							foreach ( Activity activity in activities ) {
								if ( activity.Name == method.ActivityName ) {
									found = true;
									break;
								}
							}
							if ( !found ) {
								CodeMemberMethod meth = deployment.getMethodFromCode(this.CodeBesideCCU, this.FullClassName, method.MethodName);
								if ( meth != null ) {
									if ( codeBesideccu.Namespaces.Count > 0 && codeBesideccu.Namespaces[0].Types.Count > 0 ) {
										codeBesideccu.Namespaces[0].Types[0].Members.Remove(meth);
									}
								}
								methods.Remove(method);

								continue;
							}
						}
					}
				} catch { }

				addMethodCodeSnippetsToCodeBeside(deployment);
				#endregion

				#region generate proxy
				if ( this.Workflow.BuildType == WorkflowBuildType.WCF_WindowsForm ) {
					generateProxyForMashup(deployment);
				} else if ( this.Workflow.BuildType == WorkflowBuildType.WCF_IIS ) {
					generateProxyForWCFService(deployment);
				}
				if ( Workflow.ExtendedProperties.UseDefaultPersistence ) {
					_configuration.AppSettings.Settings.Add(
						"PersistenceConnection", Workflow.ExtendedProperties.DefaultPersistenceConnection);
				}
				if ( Workflow.ExtendedProperties.UseDefaultTracking ) {
					_configuration.AppSettings.Settings.Add(
						"TrackingConnection", Workflow.ExtendedProperties.DefaultTrackingConnection);
				}
				#endregion

				#region set variables
				bool foundFirstAct = false;
				//bool hasStartAct = false;
				_workflow.ExtendedProperties.HasHumanActivity = false;
				#endregion

				#region TIMER
#if TIMER
				TimeSpan ts0 = DateTime.Now - dtStart;
				Debug.WriteLine("Pre Act Duration: " + ts0.ToString(/*"hh:mm:ss.fffffff"*/));
#endif
				#endregion

				SortedList<string, string> objectsToSerialize = new SortedList<string, string>();

				foreach ( Activity act in activities ) {

					#region TIMER
#if TIMER
					Debug.WriteLine("---");
					Debug.WriteLine("Start Activity '" + act.Name + "': " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
					DateTime dtActStart = DateTime.Now;
#endif
					#endregion

					#region IF not fount first activity
					if ( !foundFirstAct ) {
						if ( act is WebServiceInputActivity || act is HandleExternalEventActivity ||
							 act is LogicalInputActivity ) {
							foundFirstAct = true;
							//hasStartAct = true;
							if ( act is LogicalInputActivity ) {
								LogicalInputActivity lia = (LogicalInputActivity)act;
								LogicalActivity la = repSvc.GetItem<LogicalActivity>(lia.LogicalActivityId);
								if ( la != null ) {
									WorkflowEvent we = repSvc.GetItem<WorkflowEvent>(la.WorkflowEventID);
									_workflow.StartName = we.Name;
									_workflow.StartDescription = we.Description;
									_workflow.InputBusinessObject = we.BusinessObject;
								}
							}
						} else if ( !( act is CompositeActivity ) ) {
							foundFirstAct = true;
							//hasStartAct = false;
						}
					}
					#endregion

					if ( act is LogicalAsyncStartActivity ) {
						CodeMemberField field = new CodeMemberField(typeof(string), string.Format("{0}CorrelationId", act.Name));
						field.InitExpression = new CodePrimitiveExpression(null);
						field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
						_ctdServices.Members.Add(field);
					}
					try {
						// if logical activity
						if ( act is LogicalCapabilityActivity ) {
							#region generate LogicalCapabilityActivity code
							bool isHumanActivity = false;
							bool useProxy = false;
							string endpointConfigName = null;
							currentSvcGenType = ServiceGenerationType.Unknown;

							//XmlSchemaSet xsdset;
							CodeTypeReference typeRefLogActContract = null;

							// get logical activity
							LogicalCapabilityActivity logcap = (LogicalCapabilityActivity)act;
							IDesigner idesigner = (IDesigner)host.GetDesigner(logcap);

							if ( logcap.ActivitiesClass == null ) {
								if ( idesigner != null ) {
									ActivityBind actbindIn = new ActivityBind(this.ClassName, "LogicalActivitiesClass");
									logcap.SetBinding(LogicalCapabilityActivity.ActivitiesClassProperty, actbindIn);
									idesigner.Initialize(logcap);
								}
							}

							Type t = typeProvider.GetType(this.Namespace + ".ServiceCalls");
							CodeTypeReference typeRefSvcCalls = new CodeTypeReference(t);

							#region LogicalAsyncEndActivity
							if ( logcap.LogicalActivityId <= 0 ) {
								if ( logcap is LogicalAsyncEndActivity ) {
									CompositeActivity rootAct = logcap.GetRootActivity() as CompositeActivity;
									LogicalAsyncEndActivity endAct = logcap as LogicalAsyncEndActivity;
									string startActName = logcap.GetValue(LogicalAsyncEndActivity.StartActivityNameProperty) as string;
									if ( string.IsNullOrEmpty(startActName) ) continue;
									LogicalAsyncStartActivity startAct = null;
									foreach ( Activity tact in activities ) {
										if ( tact.Name == startActName ) {
											startAct = tact as LogicalAsyncStartActivity;
											break;
										}
									}
									if ( startAct == null ) continue;
									if ( string.IsNullOrEmpty(startAct.LogicalActivityName) ) continue;
									LogicalActivity startLogAct = Global.Data.RepositoryService.GetItem<LogicalActivity>(startAct.LogicalActivityId);
									if ( startLogAct == null ) continue;
									CodeMemberMethod methodCallbackLogAct = new CodeMemberMethod();
									methodCallbackLogAct.Name = "Receive" + startAct.LogicalActivityName; ;
									methodCallbackLogAct.Attributes = MemberAttributes.Final | MemberAttributes.Public;
									methodCallbackLogAct.Parameters.Add(
										new CodeParameterDeclarationExpression(
											typeof(ActivityExecutionContext), "context"));
									methodCallbackLogAct.Parameters.Add(
										new CodeParameterDeclarationExpression(
											typeof(ITrackingActivity), "activity"));
									CodeConditionStatement conditionIsSim =
										new CodeConditionStatement();
									methodCallbackLogAct.Statements.Add(conditionIsSim);

									// if ( (this._orchestration.IsSimulation == true) &&
									//		(this._orchestration.SimulateAllLogicalActivities == true) )
									conditionIsSim.Condition =
										new CodeBinaryOperatorExpression(
											new CodeBinaryOperatorExpression(
												new CodePropertyReferenceExpression(
													new CodeFieldReferenceExpression(
														new CodeThisReferenceExpression(),
														"_orchestration"),
													"IsSimulation"),
												CodeBinaryOperatorType.ValueEquality,
												new CodePrimitiveExpression(true)),
											CodeBinaryOperatorType.BooleanAnd,
											new CodeBinaryOperatorExpression(
												new CodePropertyReferenceExpression(
													new CodeFieldReferenceExpression(
														new CodeThisReferenceExpression(),
														"_orchestration"),
													"SimulateAllLogicalActivities"),
												CodeBinaryOperatorType.ValueEquality,
												new CodePrimitiveExpression(true)));
									CodeStatementCollection call = generateLogActCallbackServiceCall(startAct, startLogAct, typeRefSvcCalls);
									conditionIsSim.FalseStatements.AddRange(call);
									_ctdLogActs.Members.Add(methodCallbackLogAct);
									refreshTypeProvider(ref typeProvider, ref _codeLogActivities);

								}
								continue;
							}
							#endregion

							if ( existsLogicalActivityMethod(logcap.LogicalActivityName) ) {
								continue;
							}
							Repository.LogicalActivity logact =
								repSvc.GetItem<Repository.LogicalActivity>(logcap.LogicalActivityId);
							if ( logact == null ) {
								logcap.LogicalActivityId = -1;
								logcap.LogicalActivityName = "";
								setActivityProperty(logcap, "Capability", null);
								throw new Exception(string.Format("Please reassign this activity to a capability. name: {0}", act.Name));

							}
							if ( logact.VerbID <= 0 ) {
								logcap.LogicalActivityId = -1;
								logcap.LogicalActivityName = "";
								setActivityProperty(logcap, "Capability", null);
								throw new Exception(string.Format("Please reassign this activity to a capability. name: {0}", act.Name));
								//continue;
							}
							if ( logact.WorkflowID != this.Workflow.ID ) {
								logact.WorkflowID = this.Workflow.ID;
								logact.Save();
							}
							if ( logact.HasOutputBusinessObject ) {
								logact.OutputVariableName = act.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
							}
							if ( logact.HumanActivityID > 0 ) {
								bool changed = false;
								if ( string.IsNullOrEmpty(logact.ExtendedProperties.HumanComponentProperties.ProcessName) ) {
									logact.ExtendedProperties.HumanComponentProperties.ProcessName = Workflow.Name;
									changed = true;
								}
								if ( string.IsNullOrEmpty(logact.ExtendedProperties.HumanComponentProperties.ActivityName) ) {
									logact.ExtendedProperties.HumanComponentProperties.ActivityName = logcap.Text;
								}
								if ( string.IsNullOrEmpty(logact.ExtendedProperties.HumanComponentProperties.Subject) ) {
									logact.ExtendedProperties.HumanComponentProperties.Subject = "No Subject";
								}
								if ( changed ) logact.Save();
							}
							logcap.LogicalActivityName = logact.Name;
							// get logical operation
							//Repository.Operation op = logact.GetAssignedOperation();
							// get logical capability
							Repository.Verb verb = logact.Verb;
							// get logical method
							Repository.LogicalWebMethod logwmeth = logact.LogicalMethod;
							// webservice/method
							Repository.WebMethod webmeth = null;
							Repository.WebMethod webmethCallback = null;
							Repository.WebService websvc = null;
							// MSMQ
							Repository.MessageQueueEx sendMsmq = null;
							Repository.MessageQueueEx receiveMsmq = null;
							// human activity
							Repository.HumanActivity hact = null;
							List<LogicalRuleResultEPInfos> lstLogRuleResultEPInfos =
								new List<LogicalRuleResultEPInfos>();

							if ( verb != null ) {
								logcap.Capability = verb.Name;
							} else {
								logcap.Capability = "";
							}

							#region initialize rule endpoints, webservice, webmethod and human activity
							if ( logwmeth != null ) {
								if ( logwmeth.IsAssignedTo == LogicalMethodAssignedTo.EndpointRule ) {
									if ( !_listRuleIDs.Contains(logwmeth.EndpointRuleID) ) {
										_listRuleIDs.Add(logwmeth.EndpointRuleID);
									}
									BindingListEx<LogicalRuleResultEndpoint> lstEPs =
										logwmeth.GetLogicalRuleResultEndpoints();
									if ( lstEPs != null ) {
										foreach ( var item in lstEPs ) {
											lstLogRuleResultEPInfos
												.Add(new LogicalRuleResultEPInfos(item));
										}
									}
									hact = null;
									useProxy = false;
								} else if ( logwmeth.IsAssignedTo == LogicalMethodAssignedTo.MessageQueue ) {
									sendMsmq = logwmeth.SendMessageQueue;
									receiveMsmq = logwmeth.ReceiveMessageQueue;
									//hact = null;
								} else {
									if ( logwmeth.ProxyWebMethodID > 0 ) {
										websvc = logwmeth.GetAssignedProxyWebService();
										webmeth = logwmeth.GetAssignedProxyWebMethod();
										webmethCallback = logwmeth.GetProxyCallbackWebMethod();
										hact = null;
										useProxy = true;
									} else {
										websvc = logwmeth.GetAssignedWebService();
										webmeth = logwmeth.GetAssignedWebMethod();
										webmethCallback = logwmeth.GetCallbackWebMethod();
										hact = logwmeth.GetAssignedHumanActivity();//logact.GetHumanActivity();
									}
								}
							} else {
								websvc = logact.GetWebService();
								webmeth = logact.GetWebMethod();
								webmethCallback = null;// logwmeth.GetCallbackWebMethod();
								hact = logact.GetHumanActivity();
							}

							// create process_activity for HumanComponent
							if ( hact != null ) {
								websvc = hact.WebService;
								if ( websvc != null ) addHumanActivity(logact, websvc.Uri);
								isHumanActivity = true;
								_workflow.ExtendedProperties.HasHumanActivity = true;
							}

							currentSvcGenType = ServiceGenerationType.Unknown;
							if ( websvc != null ) {
								// set current ServiceGenerationType
								if ( websvc.Type == WebService.ServiceType.APIService ) {
									currentSvcGenType = ServiceGenerationType.APIService;
								} else if ( isHumanActivity ) {
									currentSvcGenType = ServiceGenerationType.HumanActivityService;
								} else if ( websvc.Uri.ToLower().EndsWith(".asmx") ) {
									currentSvcGenType = ServiceGenerationType.SystemWebService;
								} else if ( websvc.Uri.ToLower().EndsWith(".svc") ) {
									currentSvcGenType = ServiceGenerationType.WCFService;
								} else {
									currentSvcGenType = ServiceGenerationType.Unknown;
								}
								// get result web method
								if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
									BindingListEx<Repository.WebMethod> lstWMResult =
										Global.Data.GetRepositoryHierarchyChildRepositoryList<Repository.WebMethod>(
											OpenComposite.EII.Repository.ItemType.WebService, websvc.ID, OpenComposite.EII.Repository.ItemType.WebMethod);
									if ( lstWMResult != null && lstWMResult.Count > 0 ) {
										foreach ( Repository.WebMethod wm in lstWMResult ) {
											if ( wm.Name == "DoHumanActivity" ) {
												webmeth = wm;
											} else if ( wm.Name == "HumanResponse" ) {
												webmethCallback = wm;
											}
										}
									}
								}
							}
							#endregion

							#region generate Data classes
							///////////////////////////
							if ( logact.HasInputBusinessObject ) {
								deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
									typeProvider, logact.InputBusinessObject, this.GenerateDataContract);
							}
							if ( logact.HasOutputBusinessObject ) {
								deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
									typeProvider, logact.OutputBusinessObject, this.GenerateDataContract);
							}
							if ( logwmeth != null ) {
								if ( logwmeth.InputBusinessObject != null && logwmeth.InputBusinessObject.Schema != null ) {
									deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
										typeProvider, logwmeth.InputBusinessObject, this.GenerateDataContract);
								}
								if ( logwmeth.OutputBusinessObject != null && logwmeth.OutputBusinessObject.Schema != null ) {
									deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
										typeProvider, logwmeth.OutputBusinessObject, this.GenerateDataContract);
								}
							}
							///////////////////////////
							#endregion generate Data classes

							#region get generated type of input/output business objects
							///////////////////////////
							CodeTypeReference typeRefOutput = null;
							CodeTypeReference typeRefInput = null;
							List<CodeTypeReference> listTypeRefInputLogAct = new List<CodeTypeReference>();
							getGeneratedIOTypesOfLogicalActivity(typeProvider, logact, out typeRefOutput, out typeRefInput);
							getGeneratedIOTypesOfLogicalActivity(typeProvider, logact, out typeRefOutput, ref listTypeRefInputLogAct);
							// add property for output business object to code beside
							if ( typeRefOutput != null && logact.OutputBusinessObject != null ) {
								addPropertyForBObjectToCodeBeside(typeProvider, logact.OutputBusinessObject, typeRefOutput, logact.OutputVariableName);
								objectsToSerialize.Add(logact.OutputVariableName, typeRefOutput.BaseType);
							}
							///////////////////////////
							#endregion get generated type of output business object

							if ( !simpleGenerate ) {
								#region generate Web Method Contract
								string contractnspace = "Contract";
								System.Web.Services.Description.ServiceDescription wsdl = null;
								Collection<System.ServiceModel.Channels.Binding> bindings = null;
								///////////////////////////
								if ( webmeth != null && websvc != null ) {
									deployment.GenerateWebMethodContract(currentSvcGenType, ref typeProvider,
										ref typeRefLogActContract, websvc,
										ref contractnspace, ref wsdl, ref bindings, logact,
										out endpointConfigName, this._configuration, this.ContractsCCU);
									if ( string.IsNullOrEmpty(endpointConfigName) ) {
										dicWebServiceIDEPConfigName.TryGetValue(websvc.ID, out endpointConfigName);
									} else if ( !dicWebServiceIDEPConfigName.ContainsKey(websvc.ID) ) {
										dicWebServiceIDEPConfigName.Add(websvc.ID, endpointConfigName);
									}
								} else if ( lstLogRuleResultEPInfos != null && lstLogRuleResultEPInfos.Count > 0 ) {
									foreach ( var item in lstLogRuleResultEPInfos ) {
										webmeth = item.UseProxy ?
											item.RuleResultEndpoint.ProxyWebMethod :
											item.RuleResultEndpoint.WebMethod;
										webmethCallback = item.UseProxy ?
											item.RuleResultEndpoint.ProxyCallbackWebMethod :
											item.RuleResultEndpoint.CallbackWebMethod;
										websvc = item.UseProxy ?
											item.RuleResultEndpoint.ProxyWebService :
											item.RuleResultEndpoint.WebService;
										if ( webmeth != null && websvc != null ) {
											deployment.GenerateWebMethodContract(
												currentSvcGenType, ref typeProvider,
												ref item.TypeRefLogActContract,
												websvc,
												ref item.ContractNamespace, ref item.Wsdl, ref item.Bindings,
												logact, out item.EndpointConfigName, this._configuration,
												this.ContractsCCU);
											if ( string.IsNullOrEmpty(item.EndpointConfigName) ) {
												dicWebServiceIDEPConfigName.TryGetValue(websvc.ID, out item.EndpointConfigName);
											} else if ( !dicWebServiceIDEPConfigName.ContainsKey(websvc.ID) ) {
												dicWebServiceIDEPConfigName.Add(websvc.ID, item.EndpointConfigName);
											}
										}
									}
									webmeth = null;
									webmethCallback = null;
									websvc = null;
								}
								///////////////////////////
								#endregion generate Web Method Contract

								#region generate Mapping class code
								///////////////////////////
								CodeMemberMethod methInMap = null;
								//CodeMemberMethod methInMapPhys = null;
								CodeMemberMethod methOutMap = null;
								CodeMemberMethod methContract = null;
								CodeTypeReference typeRefMapClass = new CodeTypeReference(
									typeProvider.GetType(this.Namespace + ".Mapping"));
								bool generateConfigLogPhys = _workflow.IsConfigurable;
								bool generateConfigSubscribe = _workflow.IsConfigurable;
								if ( webmeth != null && websvc != null ) {
									deployment.GenerateMapping(
										this.ContractsCCU, this.MappingCCU, _ctdMapping, _ctorMapping,
										_configuration,
										currentSvcGenType, ref typeProvider, typeRefLogActContract,
										act.Name/*logwmeth.Name*/, logact, logact.LogicalMethod, null, webmeth, webmethCallback, null, ref methInMap, ref methOutMap,
										ref methContract, typeRefMapClass, typeRefOutput, typeRefInput,
										listTypeRefInputLogAct, useProxy,
										generateConfigLogPhys,
										generateConfigSubscribe);
								} else if ( receiveMsmq != null || sendMsmq != null ) {
									if ( sendMsmq != null && receiveMsmq == null ) {
										// send mapping
										deployment.GenerateMapping(
											this.ContractsCCU, this.MappingCCU, _ctdMapping, _ctorMapping,
											_configuration,
											ServiceGenerationType.MessageQueueService, ref typeProvider, typeRefLogActContract,
											act.Name/*logwmeth.Name*/, logact, logact.LogicalMethod, null, null, null, sendMsmq, ref methInMap, ref methOutMap,
											ref methContract, typeRefMapClass, typeRefOutput, typeRefInput,
											listTypeRefInputLogAct, false,
											generateConfigLogPhys,
											generateConfigSubscribe);
									} else if ( receiveMsmq != null && sendMsmq == null ) {
										// receive mapping
										deployment.GenerateMapping(
											this.ContractsCCU, this.MappingCCU, _ctdMapping, _ctorMapping,
											_configuration,
											ServiceGenerationType.MessageQueueService, ref typeProvider, typeRefLogActContract,
											act.Name/*logwmeth.Name*/, logact, logact.LogicalMethod, null, null, null, receiveMsmq, ref methInMap, ref methOutMap,
											ref methContract, typeRefMapClass, typeRefOutput, typeRefInput,
											listTypeRefInputLogAct, false,
											generateConfigLogPhys,
											generateConfigSubscribe);
									} else {
										deployment.GenerateMapping(
											this.ContractsCCU, this.MappingCCU, _ctdMapping, _ctorMapping,
											_configuration,
											ServiceGenerationType.MessageQueueService, ref typeProvider, typeRefLogActContract,
											act.Name/*logwmeth.Name*/, logact, logact.LogicalMethod, null, null, null, sendMsmq, ref methInMap, ref methOutMap,
											ref methContract, typeRefMapClass, typeRefOutput, typeRefInput,
											listTypeRefInputLogAct, false,
											generateConfigLogPhys,
											generateConfigSubscribe);
									}
								} else if ( lstLogRuleResultEPInfos != null && lstLogRuleResultEPInfos.Count > 0 ) {
									foreach ( var item in lstLogRuleResultEPInfos ) {
										webmeth = item.UseProxy ?
											item.RuleResultEndpoint.ProxyWebMethod :
											item.RuleResultEndpoint.WebMethod;
										webmethCallback = item.UseProxy ?
											item.RuleResultEndpoint.ProxyCallbackWebMethod :
											item.RuleResultEndpoint.CallbackWebMethod;
										websvc = item.UseProxy ?
											item.RuleResultEndpoint.ProxyWebService :
											item.RuleResultEndpoint.WebService;
										if ( webmeth != null && websvc != null ) {
											deployment.GenerateMapping(
												this.ContractsCCU, this.MappingCCU, _ctdMapping, _ctorMapping,
												_configuration,
												currentSvcGenType, ref typeProvider, item.TypeRefLogActContract,
												logwmeth.Name + "_" + item.RuleResultEndpoint.EndpointRuleResult,
												logact, logact.LogicalMethod, item.RuleResultEndpoint,
												webmeth, webmethCallback, null,
												ref item.MethodInMap, ref item.MethodOutMap,
												ref item.MethodContract,
												typeRefMapClass, typeRefOutput, typeRefInput,
												listTypeRefInputLogAct,
												( item.RuleResultEndpoint.ProxyWebMethodID > 0 ),
												generateConfigLogPhys,
												generateConfigSubscribe);
										}
									}
									webmeth = null;
									webmethCallback = null;
									websvc = null;
								}
								///////////////////////////
								#endregion generate Mapping class code

								#region generate ServiceCalls class code
								///////////////////////////
								if ( webmeth != null && websvc != null ) {
									deployment.GenerateServiceCalls(
										this.ServicesCCU, _ctdServices, this.ContractsCCU, this.RulesCCU,
										currentSvcGenType, typeProvider,
										typeRefLogActContract, logcap.LogicalActivityName, true,
										webmeth, webmethCallback, websvc, null, null, logact, logcap,
										contractnspace, methInMap, methOutMap, methContract, typeRefMapClass,
										typeRefOutput, typeRefInput, listTypeRefInputLogAct, bindings,
										endpointConfigName, this.NamespaceData, this.NamespaceRules,
										false);
								} else if ( receiveMsmq != null || sendMsmq != null ) {
									deployment.GenerateServiceCalls(
										this.ServicesCCU, _ctdServices, this.ContractsCCU, this.RulesCCU,
										 ServiceGenerationType.MessageQueueService, typeProvider,
										 typeRefLogActContract, logcap.LogicalActivityName, true,
										 null, null, null, sendMsmq, receiveMsmq, logact, logcap,
										 contractnspace, methInMap, methOutMap, methContract, typeRefMapClass,
										 typeRefOutput, typeRefInput, listTypeRefInputLogAct, bindings,
										 endpointConfigName, this.NamespaceData, this.NamespaceRules,
										 false);

								} else if ( lstLogRuleResultEPInfos != null && lstLogRuleResultEPInfos.Count > 0 &&
											 logwmeth != null ) {
									// add endpoint rule to rule code
									AddRuleToCode(logwmeth.GetEndpointRule());
									foreach ( var item in lstLogRuleResultEPInfos ) {
										webmeth = item.UseProxy ?
											item.RuleResultEndpoint.ProxyWebMethod :
											item.RuleResultEndpoint.WebMethod;
										webmethCallback = item.UseProxy ?
											item.RuleResultEndpoint.ProxyCallbackWebMethod :
											item.RuleResultEndpoint.CallbackWebMethod;
										websvc = item.UseProxy ?
											item.RuleResultEndpoint.ProxyWebService :
											item.RuleResultEndpoint.WebService;
										deployment.GenerateServiceCalls(
											this.ServicesCCU, _ctdServices, this.ContractsCCU, this.RulesCCU,
											currentSvcGenType, typeProvider,
											item.TypeRefLogActContract,
											logcap.LogicalActivityName + "_" + item.RuleResultEndpoint.EndpointRuleResult,
											true,
											webmeth, webmethCallback, websvc, null, null, logact, logcap,
											item.ContractNamespace,
											item.MethodInMap, item.MethodOutMap, item.MethodContract,
											typeRefMapClass,
											typeRefOutput, typeRefInput, listTypeRefInputLogAct, item.Bindings,
											item.EndpointConfigName, this.NamespaceData, this.NamespaceRules,
											false);
									}
									webmeth = null;
									webmethCallback = null;
									websvc = null;
								}
								///////////////////////////
								#endregion generate ServiceCalls class code
							}
							#region generate LogicalActivities class code
							///////////////////////////
							// create logical activity method:
							// public void LOGACTNAME(IKPITrackingActivity activity) {...}

							CodeMemberMethod methodLogAct = new CodeMemberMethod();
							methodLogAct.Name = logcap.LogicalActivityName;
							methodLogAct.Attributes = MemberAttributes.Final | MemberAttributes.Public;
							methodLogAct.Parameters.Add(
								new CodeParameterDeclarationExpression(
									typeof(ActivityExecutionContext), "context"));
							methodLogAct.Parameters.Add(
								new CodeParameterDeclarationExpression(
									typeof(ITrackingActivity), "activity"));
							//Type t = typeProvider.GetType(this.Namespace + ".ServiceCalls");
							//CodeTypeReference typeRefSvcCalls = new CodeTypeReference(t);

							CodeConditionStatement codeConditionIsSim =
								new CodeConditionStatement();
							methodLogAct.Statements.Add(codeConditionIsSim);

							// if ( (this._orchestration.IsSimulation == true) &&
							//		(this._orchestration.SimulateAllLogicalActivities == true) )
							codeConditionIsSim.Condition =
								new CodeBinaryOperatorExpression(
									new CodeBinaryOperatorExpression(
										new CodePropertyReferenceExpression(
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(),
												"_orchestration"),
											"IsSimulation"),
										CodeBinaryOperatorType.ValueEquality,
										new CodePrimitiveExpression(true)),
									CodeBinaryOperatorType.BooleanAnd,
									new CodeBinaryOperatorExpression(
										new CodePropertyReferenceExpression(
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(),
												"_orchestration"),
											"SimulateAllLogicalActivities"),
										CodeBinaryOperatorType.ValueEquality,
										new CodePrimitiveExpression(true)));
							// add KPIs to tracking data
							BindingListEx<Repository.KPIMetric> lstMetrics = null;
							if ( verb != null ) {
								lstMetrics = verb.GetKPIMetrics();
							}
							if ( lstMetrics != null && lstMetrics.Count > 0 ) {
								codeConditionIsSim.TrueStatements.Add(
									new CodeCommentStatement("add KPIs to tracking data"));
								foreach ( Repository.KPIMetric metric in lstMetrics ) {
									codeConditionIsSim.TrueStatements.Add(
										new CodeMethodInvokeExpression(
											new CodeArgumentReferenceExpression("activity"),
											"AddKPIData",
											new CodePrimitiveExpression(metric.Name),
											new CodePrimitiveExpression(metric.Value),
											new CodePrimitiveExpression(metric.Unit),
											new CodePrimitiveExpression(metric.DataType)));
								}
							}
							//BusinessObject inputBObject = logact.GetInputBusinessObject();
							//if ( inputBObject != null ) {
							//    codeConditionIsSim.TrueStatements.Add(
							//        new CodeCommentStatement("add input object tracking data"));
							//    codeConditionIsSim.TrueStatements.Add(
							//        new CodeMethodInvokeExpression(
							//            new CodeArgumentReferenceExpression("activity"),
							//            "AddBusinessObjectData",
							//            new CodePrimitiveExpression(inputBObject.Name),
							//            new CodePropertyReferenceExpression(
							//                new CodeFieldReferenceExpression(
							//                    new CodeThisReferenceExpression(),
							//                    "_orchestration"),
							//                    inputBObject.Name)));

							//}
							//BusinessObject outputBObject = logact.GetOutputBusinessObject();
							//if ( outputBObject != null ) {
							//    codeConditionIsSim.TrueStatements.Add(
							//        new CodeCommentStatement("add output object tracking data"));
							//    codeConditionIsSim.TrueStatements.Add(
							//        new CodeMethodInvokeExpression(
							//            new CodeArgumentReferenceExpression("activity"),
							//            "AddBusinessObjectData",
							//            new CodePrimitiveExpression(outputBObject.Name),
							//            new CodePropertyReferenceExpression(
							//                new CodeFieldReferenceExpression(
							//                    new CodeThisReferenceExpression(),
							//                    "_orchestration"),
							//                    outputBObject.Name)));
							//}
							// else ( no Simulation )
							RepositoryBusinessRule epRule = null;
							if ( logwmeth != null ) epRule = logwmeth.GetEndpointRule();

							CodeStatementCollection statements = generateLogActServiceCall(
								logcap, logact, null/*op*/, verb, websvc, logcap is LogicalAsyncEndActivity ? receiveMsmq : sendMsmq,
								epRule, lstLogRuleResultEPInfos,
								typeRefOutput, typeRefInput,
								typeRefSvcCalls);

							codeConditionIsSim.FalseStatements.AddRange(statements);

							_ctdLogActs.Members.Add(methodLogAct);
							refreshTypeProvider(ref typeProvider, ref _codeLogActivities);
							///////////////////////////
							#endregion generate LogicalActivities class code

							#endregion
						} else if ( act is DataAggregatorActivity ) {
							#region generate DataAggregatorActivity code
							DataAggregatorActivity daact = (DataAggregatorActivity)act;
							if ( daact.LogicalActivityId <= 0 )
								continue;
							if ( daact.ActivitiesClass == null ) {
								IDesigner idesigner = (IDesigner)host.GetDesigner(daact);
								if ( idesigner != null ) {
									ActivityBind actbindIn = new ActivityBind(this.ClassName, "LogicalActivitiesClass");
									daact.SetBinding(DataAggregatorActivity.ActivitiesClassProperty, actbindIn);
									idesigner.Initialize(daact);
								}
							}
							LogicalActivity logact = repSvc.GetItem(ItemType.LogicalActivity,
								daact.LogicalActivityId, true) as LogicalActivity;

							if ( logact == null || logact.OutputBusinessObjectID <= 0 )
								continue;

							Repository.BusinessObject boOutput = logact.GetOutputBusinessObject();
							if ( boOutput == null || boOutput.Schema == null ) continue;

							logact.OutputVariableName = act.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
							#region generate Data classes
							///////////////////////////
							// add output schema classes
							deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
								typeProvider, boOutput, this.GenerateDataContract);
							///////////////////////////
							#endregion generate Data classes

							#region generate Mapping class code
							///////////////////////////
							CodeMemberMethod methMap = null;
							CodeTypeReference typeRefMapClass =
								new CodeTypeReference(typeProvider.GetType(this.Namespace + ".Mapping"));
							// get mapping
							XsltDocument xslt = logact.InputXslt;
							if ( xslt == null ) {
								continue;
							}

							// get input and output type references
							CodeTypeReference typeRefOutput;
							List<CodeTypeReference> listTypeRefInput = new List<CodeTypeReference>();
							getGeneratedIOTypesOfDataAggregation(typeProvider, boOutput, logact,
								out typeRefOutput, ref listTypeRefInput);

							// add property for output business object to code beside
							if ( typeRefOutput != null && boOutput != null ) {
								addPropertyForBObjectToCodeBeside(typeProvider, boOutput, typeRefOutput, logact.OutputVariableName);
							}
							///////////////////////////

							// use / is configurable
							bool generateConfigSubscribe = _workflow.IsConfigurable;

							// save xslt as constant strings
							CodeMemberField fieldXslt = null;
							if ( xslt != null && xslt.DocumentElement != null ) {
								fieldXslt = new CodeMemberField(typeof(string), "xsltInput" + daact.LogicalActivityName);
								if ( generateConfigSubscribe ) {
									fieldXslt.Attributes = MemberAttributes.Private;
								} else {
									fieldXslt.Attributes = MemberAttributes.Private | MemberAttributes.Const;
								}
								fieldXslt.InitExpression = new CodePrimitiveExpression(xslt.DocumentElement.OuterXml);
							}

							// generate mapping method
							methMap = deployment.GenerateMappingMethodForSubscriptions(
								typeProvider, daact.LogicalActivityName, listTypeRefInput,
								typeRefMapClass, fieldXslt, null,
								false,
								generateConfigSubscribe,
								logact.ExtendedProperties.InputCodeMapping, new List<Type>(), null, typeRefOutput);
							_ctdMapping.Members.Add(fieldXslt);
							_ctdMapping.Members.Add(methMap);

							refreshTypeProvider(ref typeProvider, ref _codeLogActivities);
							///////////////////////////
							#endregion generate Mapping class code

							#region generate LogicalActivities class code
							///////////////////////////
							CodeMemberMethod methodLogAct = new CodeMemberMethod();
							methodLogAct.Name = daact.LogicalActivityName;
							methodLogAct.Attributes = MemberAttributes.Final | MemberAttributes.Public;
							Type t = typeProvider.GetType(this.Namespace + ".Mapping");
							Type typeOutput = typeProvider.GetType(this.Namespace + ".Data." + boOutput.Name);

							CodeExpression mapAggTargetObj =
								( methMap.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
								(CodeExpression)new CodeTypeReferenceExpression(typeRefMapClass) :
								(CodeExpression)new CodePropertyReferenceExpression(
									new CodeFieldReferenceExpression(
										new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
									"Mapping");

							CodeMethodInvokeExpression methCallMapping =
								new CodeMethodInvokeExpression(
									new CodeMethodReferenceExpression(
										mapAggTargetObj,
										methMap.Name));

							NamedBusinessObjectCollection subscriptions = logact.GetSubscribedBusinessObjects();
							if ( subscriptions.Count > 0 ) {
								foreach ( NamedBusinessObject item in subscriptions ) {
									methCallMapping.Parameters.Add(
										new CodePropertyReferenceExpression(
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
												item.Name + Deployment.cBObjPropSuffix));
								}
							}
							if ( typeRefOutput != null ) {
								methodLogAct.Statements.Add(	// OUTPUTTYPE output = null;
									new CodeVariableDeclarationStatement(
										typeOutput,
										"output",
										new CodePrimitiveExpression(null)));
								methodLogAct.Statements.Add(	// XmlDocument xdOutput = methodMapping(input0, input1, ...);
									new CodeVariableDeclarationStatement(
										typeof(XmlDocument),
										"xdOutput",
										methCallMapping));
								methodLogAct.Statements.Add(	// MemoryStream msOutput = new MemoryStream();
									new CodeVariableDeclarationStatement(
										typeof(MemoryStream),
										"msOutput",
										new CodeObjectCreateExpression(typeof(MemoryStream))));
								methodLogAct.Statements.Add( // xdOutput.Save(msOutput);
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("xdOutput"),
										"Save",
										new CodeVariableReferenceExpression("msOutput")));
								methodLogAct.Statements.Add(	// msOutput.Position = 0;
									new CodeAssignStatement(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("msOutput"),
											"Position"),
										new CodePrimitiveExpression(0)));
								methodLogAct.Statements.Add(	// object obj = null;
									new CodeVariableDeclarationStatement(
										typeof(object),
										"obj",
										new CodePrimitiveExpression(null)));
								// use XmlSerialzer
								// XmlRootAttribute root = new XmlRootAttribute(TYPENAME);
								methodLogAct.Statements.Add(
									new CodeVariableDeclarationStatement(
										typeof(XmlRootAttribute),
										"root",
										new CodeObjectCreateExpression(
											typeof(XmlRootAttribute),
											new CodePrimitiveExpression(boOutput.Name))));
								// root.Namespace = xdOuput.DocumentElement.NamespaceURI;
								methodLogAct.Statements.Add(
									new CodeAssignStatement(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("root"),
											"Namespace"),
										new CodePropertyReferenceExpression(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression("xdOutput"),
												"DocumentElement"),
											"NamespaceURI")));
								object[] attibs = typeOutput.GetCustomAttributes(typeof(DataContractAttribute), false);
								if ( attibs == null || attibs.Length == 0 ) {
									// XmlSerializer xsOutput = new XmlSerializer(typeof(OUTPUTTYPE), root);
									methodLogAct.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(XmlSerializer),
											"xsOutput",
											new CodeObjectCreateExpression(
												typeof(XmlSerializer),
												new CodeTypeOfExpression(typeOutput),
												new CodeVariableReferenceExpression("root"))));
									methodLogAct.Statements.Add(	// obj = xsOutput.Deserialize(msOutput);
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("obj"),
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xsOutput"),
												"Deserialize",
												new CodeVariableReferenceExpression("msOutput"))));
								} else {
									// DataContractSerializer xs = new DataContractSerializer(typeof(OUTPUTTYPE), root.Name, root.Namespace);
									methodLogAct.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(DataContractSerializer),
											"xsOutput",
											new CodeObjectCreateExpression(
												typeof(DataContractSerializer),
												new CodeTypeOfExpression(typeOutput),
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("root"), "ElementName"),
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("root"), "Namespace"))));
									methodLogAct.Statements.Add(	// obj = xsOutput.ReadObject(msOutput);
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("obj"),
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xsOutput"),
												"ReadObject",
												new CodeVariableReferenceExpression("msOutput"))));
								}
								methodLogAct.Statements.Add(	// if ( obj.GetType() == OUTPUTTYPE )
									new CodeConditionStatement(
										new CodeBinaryOperatorExpression(
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("obj"),
												"GetType"),
											CodeBinaryOperatorType.ValueEquality,
											new CodeTypeOfExpression(typeOutput)),
										new CodeStatement[] {
										new CodeAssignStatement(	// output = (OUTPUTTYPE)obj;
											new CodeVariableReferenceExpression("output"),
											new CodeCastExpression(
												typeOutput,
												new CodeVariableReferenceExpression("obj"))),
									},
										new CodeStatement[] {	// else
										new CodeAssignStatement(	// output = null;
											new CodeVariableReferenceExpression("output"),
											new CodePrimitiveExpression(null))
									}));
								methodLogAct.Statements.Add(	// msOutput.Close();
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("msOutput"),
										"Close"));
								methodLogAct.Statements.Add(	// _orchestration.BOBJECT = output;
									new CodeAssignStatement(
										new CodePropertyReferenceExpression(
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
												logact.OutputVariableName + Deployment.cBObjPropSuffix),
										new CodeVariableReferenceExpression("output")));
							}
							_ctdLogActs.Members.Add(methodLogAct);
							refreshTypeProvider(ref typeProvider, ref _codeLogActivities);
							///////////////////////////
							#endregion generate LogicalActivities class code

							#endregion
						} else if ( act is RuleEvaluatorActivity ) {
							#region generate RuleEvaluatorActivity code
							RuleEvaluatorActivity rea = (RuleEvaluatorActivity)act;
							if ( rea.LogicalActivityId <= 0 )
								continue;
							if ( rea.ActivitiesClass == null ) {
								IDesigner idesigner = (IDesigner)host.GetDesigner(rea);
								if ( idesigner != null ) {
									ActivityBind actbindIn = new ActivityBind(this.ClassName, "LogicalActivitiesClass");
									rea.SetBinding(RuleEvaluatorActivity.ActivitiesClassProperty, actbindIn);
									idesigner.Initialize(rea);
								}
							}

							LogicalActivity logact = repSvc.GetItem(ItemType.LogicalActivity,
								rea.LogicalActivityId, true) as LogicalActivity;

							if ( logact == null || logact.OutputBusinessObjectID <= 0 )
								continue;

							Repository.BusinessObject boOutput = logact.GetOutputBusinessObject();
							Repository.RepositoryBusinessRule brule = logact.GetBusinessRule();
							if ( boOutput == null || boOutput.Schema == null || brule == null ||
								 string.IsNullOrEmpty(logact.ExtendedProperties.BusinessRuleOutputPath) )
								continue;

							#region create output data code and property
							deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
								typeProvider, boOutput, this.GenerateDataContract);

							Type typeBOOut = typeProvider.GetType(
								this.NamespaceData + "." + boOutput.Name);
							if ( typeBOOut == null )
								throw new InvalidOperationException("The output business object \"" + boOutput.Name + "\" does not exists in the current process.");

							CodeTypeReference typeRefOutput = new CodeTypeReference(typeBOOut);
							if ( typeRefOutput == null )
								throw new InvalidOperationException("The output business object \"" + boOutput.Name + "\" does not exists in the current process.");

							if ( typeRefOutput != null ) {
								addPropertyForBObjectToCodeBeside(typeProvider, boOutput, typeRefOutput, logact.OutputVariableName);
								objectsToSerialize.Add(logact.OutputVariableName, typeRefOutput.BaseType);
							}
							#endregion

							#region generate LogicalActivities class code
							///////////////////////////
							CodeMemberMethod methodLogAct = new CodeMemberMethod();
							methodLogAct.Name = rea.LogicalActivityName;
							methodLogAct.Attributes = MemberAttributes.Final | MemberAttributes.Public;

							// string result = Rules.RULE_NAME(_orchestration.PARAM_1[,...]);
							List<CodeExpression> lstRuleParams = new List<CodeExpression>();
							foreach ( string paramname in brule.GetParameters().Keys ) {
								lstRuleParams.Add(
									new CodePropertyReferenceExpression(
										new CodeFieldReferenceExpression(
											new CodeThisReferenceExpression(),
											"_orchestration"),
										paramname));
							}
							string rulesclass = this.NamespaceRules + ".Rules";
							CodeMemberMethod methodRule = Helpers.GetMember<CodeMemberMethod>(
								_codeRules, rulesclass, brule.Name);
							if ( methodRule == null ) {
								throw new NullReferenceException(
									string.Format("The rule \"{0}\" was not generated correctly.", brule.Name));
							}
							CodeExpression rulesTargetObj =
								( methodRule.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
								(CodeExpression)new CodeTypeReferenceExpression(this.NamespaceRules + ".Rules") :
								(CodeExpression)new CodePropertyReferenceExpression(
									new CodeFieldReferenceExpression(
										new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
									"Rules");
							CodeMethodInvokeExpression methinvoke = new CodeMethodInvokeExpression(
								rulesTargetObj,
								brule.Name,
								lstRuleParams.ToArray());
							methodLogAct.Statements.Add(
								new CodeVariableDeclarationStatement(
									typeof(string),
									"result",
									methinvoke));

							string[] resultPath = logact.ExtendedProperties.BusinessRuleOutputPath.Split('.');
							if ( resultPath.Length <= 1 ) {
								throw new Exception(string.Format(
									"Invalid result path selected.{0}{0}Please select a field of an business object in the Rule Evaluator configuration dialog.",
									Environment.NewLine));
							}
							resultPath[0] = logact.OutputVariableName;
							if ( resultPath.Length > 2 ) {
								throw new Exception(
									"In this version it is not possible to select " +
									"a field from child business objects.");
							}
							// foreach
							CodeExpression expPath = new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(),
								"_orchestration");
							for ( int i = 0; i < resultPath.Length - 1; i++ ) {
								// if ( _orchestration.RESULT_OBJECT == null )
								// _orchestration.RESULT_OBJECT = new RESULT_OBJECT_TYPE();
								expPath = new CodePropertyReferenceExpression(
									expPath,
									resultPath[i]);
								CodeConditionStatement cond = new CodeConditionStatement(
									new CodeBinaryOperatorExpression(
										expPath,
										CodeBinaryOperatorType.ValueEquality,
										new CodePrimitiveExpression(null)),
									new CodeAssignStatement(
										expPath,
										new CodeObjectCreateExpression(typeRefOutput)));

								methodLogAct.Statements.Add(cond);
							}
							expPath = new CodePropertyReferenceExpression(
								expPath,
								resultPath[resultPath.Length - 1]);
							// _orchestration.RESULT_OBJECT.RESULT_FIELD = result;
							methodLogAct.Statements.Add(
								new CodeAssignStatement(
									expPath,
									new CodeVariableReferenceExpression("result")));

							_ctdLogActs.Members.Add(methodLogAct);
							refreshTypeProvider(ref typeProvider, ref _codeLogActivities);
							#endregion

							#endregion
						} else if ( act is LogicalMethodCallActivity ) {
							#region LogicalMethodCallActivity
							initLogicalMethodCallActivity(host, repSvc, typeProvider, act, deployment);
							#endregion
						} else if ( act is LogicalInputActivity ) {
							#region LogicalInputActivity
							initLogicalInputActivity(host, repSvc, typeProvider, act, deployment);
							#endregion
						} else if ( act is NotificationActivity ) {
							#region NotificationActivity
							NotificationActivity notifcation = (NotificationActivity)act;
							LogicalActivity logact = repSvc.GetItem<LogicalActivity>(notifcation.LogicalActivityId);
							if ( logact == null ) {
								throw new Exception(
									string.Format("Please configurate the notification activity \"{0}\".",
									notifcation.Text.Replace(Environment.NewLine, "").Replace("\t", "")));
							}
							IDesigner idesigner = (IDesigner)host.GetDesigner(notifcation);
							Debug.Assert(idesigner != null);
							notifcation.ParameterBindings.Clear();
							foreach ( var bobj in logact.GetSubscribedBusinessObjects() ) {
								if ( bobj.Name == null ) continue;
								WorkflowParameterBinding wpb = new WorkflowParameterBinding();
								wpb.ParameterName = bobj.Name;
								wpb.SetBinding(
									WorkflowParameterBinding.ValueProperty,
									new ActivityBind(this.ClassName, bobj.Name));
								notifcation.ParameterBindings.Add(wpb);
							}
							if ( notifcation.ActivitiesClass == null ) {
								ActivityBind actbindIn = new ActivityBind(this.ClassName, "LogicalActivitiesClass");
								notifcation.SetBinding(NotificationActivity.ActivitiesClassProperty, actbindIn);
							}
							idesigner.Initialize(notifcation);

							if ( !simpleGenerate ) {
								string hostName = string.Format(NotificationActivity.HostKey, act.Name);
								string sender = string.Format(NotificationActivity.SenderKey, act.Name);
								string userName = string.Format(NotificationActivity.UserNameKey, act.Name);
								string password = string.Format(NotificationActivity.PasswordKey, act.Name);
								string recipient = string.Format(NotificationActivity.RecipientKey, act.Name);
								string subject = string.Format(NotificationActivity.SubjectKey, act.Name);
								string message = string.Format(NotificationActivity.MessageKey, act.Name);
								KeyValueConfigurationElement kvceHost =
									new KeyValueConfigurationElement(hostName, notifcation.NotificationHost);
								KeyValueConfigurationElement kvceSender =
									new KeyValueConfigurationElement(sender, notifcation.NotificationSender);
								KeyValueConfigurationElement kvceUser =
									new KeyValueConfigurationElement(userName, notifcation.NotificationUserName);
								KeyValueConfigurationElement kvcePassword =
									new KeyValueConfigurationElement(password, notifcation.NotificationPassword);
								KeyValueConfigurationElement kvceRecipient =
									new KeyValueConfigurationElement(recipient, notifcation.Notification == null ? null : notifcation.Notification.Recipient);
								KeyValueConfigurationElement kvceSubject =
									new KeyValueConfigurationElement(subject, notifcation.Notification == null ? null : notifcation.Notification.Subject);
								KeyValueConfigurationElement kvceMessage =
									new KeyValueConfigurationElement(message, notifcation.Notification == null ? null : notifcation.Notification.Message);
								_configuration.AppSettings.Settings.Add(kvceHost);
								_configuration.AppSettings.Settings.Add(kvceSender);
								_configuration.AppSettings.Settings.Add(kvceUser);
								_configuration.AppSettings.Settings.Add(kvcePassword);
								_configuration.AppSettings.Settings.Add(kvceRecipient);
								_configuration.AppSettings.Settings.Add(kvceSubject);
								_configuration.AppSettings.Settings.Add(kvceMessage);
							}
							#endregion
						} else if ( act is ExtendedCodeActivity ) {
							#region ExtendedCodeActivity
							ExtendedCodeActivity codeAct = (ExtendedCodeActivity)act;
							IDesigner idesigner = (IDesigner)host.GetDesigner(codeAct);
							Debug.Assert(idesigner != null);
							if ( codeAct.ActivitiesClass == null ) {
								ActivityBind actbindIn = new ActivityBind(this.ClassName, "LogicalActivitiesClass");
								codeAct.SetBinding(ExtendedCodeActivity.ActivitiesClassProperty, actbindIn);
							}
							idesigner.Initialize(codeAct);

							#endregion
						}
					} catch ( Exception ex ) {

						#region display error
						if ( taskList == null ) {
							string msg = string.Format(
								"Error while generating code for activity '{0}'.{1}{1}{2}",
								act.Name, Environment.NewLine, ex.Message);
							//MessageBox.Show(msg, "Generate Logical Activities Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
							throw new Exception(msg, ex);
						} else {
							string msg = string.Format("Activity '{0}': {1}", act.Name, ex.Message);
							if ( ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message) ) {
								msg += Environment.NewLine + "Inner Exception: " + ex.InnerException.Message;
							}
							taskList.Add(_workflow, TaskItemType.Error, TaskStatus.None, ex, msg, cTaskListSourceNameGenerate);
						}
						#endregion

					}

					#region TIMER
#if TIMER
					TimeSpan ts = DateTime.Now - dtActStart;
					Debug.WriteLine("Act '" + act.Name + "' Duration: " + ts.ToString(/*"hh:mm:ss.fffffff"*/));
#endif
					#endregion

				}
				if ( this.DataCCU.Namespaces.Count > 0 &&
					this.DataCCU.Namespaces[0].Types.Count == 0 ) {
					this.DataCCU.Namespaces[0].Types.Add(new CodeTypeDeclaration("__empty"));
				}
				implementISerializable(deployment, objectsToSerialize);


				#region verify rule parameter resolve
				bool showRebuildRulesMsg = false;
				BindingListEx<Repository.Workflow.RuleParameterResolve> lstRPR =
					new BindingListEx<OpenComposite.EII.Repository.Workflow.RuleParameterResolve>();
				int[] ruleidarray = _listRuleIDs.ToArray();
				foreach ( int idRule in ruleidarray ) {
					RepositoryBusinessRule rbr = repSvc.GetItem<RepositoryBusinessRule>(idRule);
					if ( rbr == null ) {
						_listRuleIDs.Remove(idRule);
					} else {
						BindingListEx<Repository.Workflow.RuleParameterResolve> lRuleRPR = rbr.GetRuleParameterResolveList();
						foreach ( var item in lRuleRPR ) {
							if ( item.ParameterID <= 0 ) {
								showRebuildRulesMsg = true;
								continue;
							}
							if ( !existsNounInResolveList(lstRPR, item.ParameterID) ) {
								lstRPR.Add(item);
							}
						}
					}
				}
				BindingListEx<Repository.Workflow.RuleParameterResolve> lstRPRExisting = _workflow.ExtendedProperties.WorkflowVariables;
				foreach ( var rprnew in lstRPR ) {
					if ( !existsNounInResolveList(lstRPRExisting, rprnew.ParameterID) ) {
						// search for an item with the same name but no ParameterID
						Repository.Workflow.RuleParameterResolve rprexisting = getRPRByName(lstRPRExisting, rprnew.ParameterName);
						if ( rprexisting != null ) {
							// set id to existing item
							rprexisting.ParameterID = rprnew.ParameterID;
						} else {
							// add new item to existing list
							lstRPRExisting.Add(rprnew);
						}
					}
				}
				foreach ( OpenComposite.EII.Repository.Workflow.RuleParameterResolve rpr in _workflow.ExtendedProperties.WorkflowVariables.ToArray() ) {
					if ( rpr.ParameterID <= 0 ) {
						showRebuildRulesMsg = true;
					} else {
						if ( !existsNounInResolveList(lstRPR, rpr.ParameterID) ) {
							_workflow.ExtendedProperties.WorkflowVariables.Remove(rpr);
							continue;
						}
					}
					bool resolvepropexists = false;
					foreach ( CodeTypeMember codeMember in codeBesideccu.Namespaces[0].Types[0].Members ) {
						CodeMemberProperty codeProp = codeMember as CodeMemberProperty;
						if ( codeProp != null &&
							 rpr.ParameterResolve != null && rpr.ParameterResolve.StartsWith(codeProp.Name) ) {
							resolvepropexists = true;
							break;
						}
					}
					if ( !resolvepropexists ) {
						rpr.ParameterResolve = null;
					}
					Type propType = OpenComposite.EII.Helpers.GetDotNetTypeOfDataTypeString(rpr.ParameterDataType);
					memberCreation.CreatePropertyForRuleParameterResolution(
						this.FullClassName, rpr.ParameterName, propType,
						rpr.ParameterResolve);

					// change property type to nullable if type is a valuetype
					if ( propType.IsValueType ) {
						Type nullableType = typeof(Nullable<>);
						propType = nullableType.MakeGenericType(propType);
					}
					addPropertyToInterface(_ctdWFInterface, propType, rpr.ParameterName, true, true);
				}
				if ( taskList != null && showRebuildRulesMsg ) {
					string msg = string.Format("Please open and save all used rule policies to initialize the new vocabulary assignment.");
					taskList.Add(_workflow, TaskItemType.Task, TaskStatus.Todo, null, msg, cTaskListSourceNameGenerate);
				}
				#endregion

				#region save configuration
				if ( !simpleGenerate ) {
					// save Configuration
					_configuration.Save(ConfigurationSaveMode.Minimal, true);
					ConfigXmlDocument xdConfig = new ConfigXmlDocument();
					xdConfig.Load(_configuration.FilePath);
					_workflow.ExtendedProperties.ConfigurationString = xdConfig.OuterXml;
				}
				#endregion

				#region disable wait cursor
				if ( wait != null ) {
					wait.Dispose();
					wait = null;
				}
				#endregion

				#region commit transaction
				if ( trans != null ) trans.Commit();
				#endregion

			} catch ( Exception ex ) {

				#region disable wait cursor
				if ( wait != null ) {
					wait.Dispose();
					wait = null;
				}
				#endregion

				#region cancel and rollback transaction
				if ( trans != null ) trans.Cancel();
				#endregion

				#region display error
				if ( taskList == null ) {
					//MessageBox.Show(ex.Message, "Generate Logical Activities Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
					throw ex;
				} else {
					string msg = string.Format("Workflow '{0}': {1}", _workflow.Name, ex.Message);
					taskList.Add(_workflow, TaskItemType.Error, TaskStatus.None, ex, msg, cTaskListSourceNameGenerate);
				}
				#endregion

			} finally {

				#region set selection
				setSelectedItem(selectedItem);
				#endregion

			}

			#region refresh type provider
			RefreshAllCode();
			#endregion

			#region TIMER
#if TIMER
			TimeSpan ts1 = DateTime.Now - dtStart;
			Debug.WriteLine("Generate Duration: " + ts1.ToString(/*"hh:mm:ss.fffffff"*/));
			Debug.WriteLine("END: " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
#endif
			#endregion
		}

		private void implementISerializable(Deployment deployment, SortedList<string, string> objectsToSerialize)
		{
			TypeProvider typeProvider = (TypeProvider)this.GetService(typeof(ITypeProvider));
			Debug.Assert(typeProvider != null);

			SortedList<string, Type> serializables = new SortedList<string, Type>();
			foreach ( WorkflowField field in _workflow.Interface.Fields ) {
				Type fieldType = typeProvider.GetType(field.DataType);
				if ( fieldType == null ) continue;
				serializables.Add(field.Name, fieldType);
			}
			foreach ( KeyValuePair<string, string> ots in objectsToSerialize ) {
				Type boType = typeProvider.GetType(ots.Value);
				if ( boType == null ) continue;
				serializables.Add(ots.Key, boType);
			}
			// create serialization Constructor
			CodeConstructor ctor = new CodeConstructor();
			ctor.Parameters.Add(
				new CodeParameterDeclarationExpression(
					typeof(SerializationInfo), "info"));
			ctor.Parameters.Add(
				new CodeParameterDeclarationExpression(
					typeof(StreamingContext), "context"));

			// create ISerialization Member (GetObjectData)
			CodeMemberMethod meth = new CodeMemberMethod();
			meth.Name = "GetObjectData";
			meth.Attributes = MemberAttributes.Public;
			meth.StartDirectives.Add(
				new CodeRegionDirective(CodeRegionMode.Start, "ISerializable Members"));
			meth.EndDirectives.Add(
				new CodeRegionDirective(CodeRegionMode.End, null));
			meth.Parameters.Add(
				new CodeParameterDeclarationExpression(
					typeof(SerializationInfo), "info"));
			meth.Parameters.Add(
				new CodeParameterDeclarationExpression(
					typeof(StreamingContext), "context"));

			foreach ( KeyValuePair<string, Type> item in serializables ) {
				ctor.Statements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodeThisReferenceExpression(),
							item.Key),
						new CodeCastExpression(
							item.Value,
							new CodeMethodInvokeExpression(
								new CodeArgumentReferenceExpression("info"),
								"GetValue",
								new CodePrimitiveExpression(item.Key),
								new CodeTypeOfExpression(item.Value)))));

				meth.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeArgumentReferenceExpression("info"),
						"AddValue",
						new CodePrimitiveExpression(item.Key),
						new CodePropertyReferenceExpression(
							new CodeThisReferenceExpression(),
							item.Key)));
			}

			foreach ( CodeConstructor mctor in _ctdBeside.Members.OfType<CodeConstructor>().ToArray() ) {
				_ctdBeside.Members.Remove(mctor);
			}

			foreach ( CodeMemberMethod mMeth in _ctdBeside.Members.OfType<CodeMemberMethod>().ToArray() ) {
				if ( mMeth.Name == "GetObjectData" ) _ctdBeside.Members.Remove(mMeth);
			}

			_ctdBeside.Members.Add(ctor);
			_ctdBeside.Members.Add(meth);
			_ctdBeside.BaseTypes.Add(
				new CodeTypeReference(typeof(ISerializable)));

			bool hasAttribute = false;
			foreach ( CodeAttributeDeclaration attr in _ctdBeside.CustomAttributes ) {
				if ( attr.AttributeType.BaseType == typeof(SerializableAttribute).FullName ) {
					hasAttribute = true;
					break;
				}
			}
			if ( !hasAttribute )
				_ctdBeside.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(SerializableAttribute))));
		}

		private void generateRuleConstantsCode(RepositoryService repSvc)
		{
			CodeConstructor ctorRules = null;
			if ( _workflow.IsConfigurable ) {
				ctorRules = new CodeConstructor();
				ctorRules.Attributes = MemberAttributes.Public;
				_ctdRules.Members.Add(ctorRules);
			}
			foreach ( int idRuleConst in _listRuleConstIDs ) {
				RuleConstant rc = repSvc.GetItem(ItemType.RuleConstant, idRuleConst, true) as RuleConstant;
				if ( rc != null ) {
					CodeMemberField fieldConst = new CodeMemberField();
					fieldConst.Name = CodeGen.ConstPrefix + rc.Name;
					fieldConst.Type = new CodeTypeReference(Global.Data.GetDOTNETTypeofXSDDataType(rc.DataType));
					if ( _workflow.IsConfigurable ) {
						fieldConst.Attributes = MemberAttributes.Private;
						if ( ctorRules != null ) {
							// add intialization to ctor
							//try {
							//    this.CONST_HighBudgetScore = Convert.ChangeType(
							//        System.Configuration.ConfigurationManager.AppSettings["CONST_HighBudgetScore"],
							//        typeof(decimal));
							//} catch { }
							CodeTryCatchFinallyStatement codeTry = new CodeTryCatchFinallyStatement();
							codeTry.TryStatements.Add(
								new CodeAssignStatement(
									new CodeFieldReferenceExpression(null, fieldConst.Name),
									new CodeCastExpression(
										Global.Data.GetDOTNETTypeofXSDDataType(rc.DataType),
										new CodeMethodInvokeExpression(
											new CodeTypeReferenceExpression(typeof(Convert)),
											"ChangeType",
											new CodeArrayIndexerExpression(
												new CodePropertyReferenceExpression(
													new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
													"AppSettings"),
												new CodePrimitiveExpression(fieldConst.Name)),
											new CodeTypeOfExpression(
												Global.Data.GetDOTNETTypeofXSDDataType(rc.DataType))))));
							codeTry.CatchClauses.Add(new CodeCatchClause());
							ctorRules.Statements.Add(codeTry);
							_configuration.AppSettings.Settings.Add(fieldConst.Name, rc.Value);
						}
					} else {
						fieldConst.Attributes = MemberAttributes.Private | MemberAttributes.Const;
					}

					object val = rc.GetValueObject();
					if ( val != null ) {
						fieldConst.InitExpression = new CodePrimitiveExpression(val);
					} else {
						fieldConst.InitExpression = new CodeDefaultValueExpression(fieldConst.Type);
					}
					_ctdRules.Members.Add(fieldConst);
				}
			}
		}

		#region Workflow Interface
		private void initLogicalMethodCallActivity(
			IDesignerHost host, RepositoryService repSvc, TypeProvider typeProvider,
			Activity act, Deployment deployment)
		{
			LogicalMethodCallActivity lma = (LogicalMethodCallActivity)act;
			LogicalActivity la = repSvc.GetItem<LogicalActivity>(lma.LogicalActivityId);
			if ( la == null && lma.LogicalActivityId > 0 ) {
				throw new Exception(string.Format("Unknown Error. Please recreate the activity '{0}' in the composite activity '{1}'.", act.Name, act.Parent.Name));
			}
			WorkflowMethod wm = repSvc.GetItem<WorkflowMethod>(la.WorkflowMethodID);
			if ( la != null && wm != null ) {
				IDesigner idesigner = (IDesigner)host.GetDesigner(lma);
				if ( idesigner != null ) {
					setActivityProperty(lma, "InterfaceType",
						typeProvider.GetType(this.Namespace + "." + _ctdLocalInterface.Name));
					setActivityProperty(lma, "MethodName", lma.LogicalActivityName);

					// check output variable name
					string outvarname = act.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
					if ( string.IsNullOrEmpty(outvarname) && wm.OutputBusinessObject != null ) {
						outvarname =
							string.Format("{0}_{1}", wm.Name, wm.OutputBusinessObjectName);
						lma.SetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty, outvarname);
					} else if ( !string.IsNullOrEmpty(outvarname) && wm.OutputBusinessObject == null ) {
						outvarname = null;
						lma.SetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty, outvarname);
					}
					bool hasOutBO = wm.OutputBusinessObject != null;
					setActivityProperty(lma, "HasOutputObject", hasOutBO);
					if ( hasOutBO ) {
						MemberCreationService memberCreate = (MemberCreationService)this.GetService(typeof(IMemberCreationService));
						Type type = null;
						deployment.AddBusinessObjectToDataCode(
							this.DataCCU, this.NamespaceData,
							typeProvider, wm.OutputBusinessObject, this.GenerateDataContract);
						type = typeProvider.GetType(
							string.Format("{0}.{1}", this.NamespaceData, wm.OutputBusinessObjectName));

						if ( la.OutputVariableName != outvarname ) {
							memberCreate.RemoveProperty(_workflow.ExtendedProperties.FullName,
														la.OutputVariableName,
														null);
						}
						memberCreate.CreateProperty(_workflow.ExtendedProperties.FullName,
													outvarname,
													type,
													null, true, false, false, null, false);
					}

					la.BeginEdit();
					la.WorkflowID = wm.WorkflowID;
					la.OutputBusinessObjectID = wm.OutputBusinessObjectID;
					if ( hasOutBO ) {
						la.OutputVariableName = outvarname;
					}
					la.EndEdit(true);

					lma.ParameterBindings.Clear();
					WorkflowParameterBinding wpb;
					// add workflow instance parameter
					wpb = new WorkflowParameterBinding();
					wpb.ParameterName = Deployment.cWorkflowInstanceId;
					wpb.SetBinding(WorkflowParameterBinding.ValueProperty,
						new ActivityBind(this.ClassName, PropertyNames.WorkflowInstanceId));
					lma.ParameterBindings.Add(wpb);
					if ( wm.InputBusinessObjectID > 0 ) {
						// add process output parameter
						wpb = new WorkflowParameterBinding();
						wpb.ParameterName = Deployment.cMethodInput;
						wpb.SetBinding(WorkflowParameterBinding.ValueProperty,
							new ActivityBind(this.ClassName, la.InputVariableName));
						lma.ParameterBindings.Add(wpb);
					}
					if ( wm.OutputBusinessObjectID > 0 ) {
						// add return value parameter
						wpb = new WorkflowParameterBinding();
						wpb.ParameterName = "(ReturnValue)";
						wpb.SetBinding(WorkflowParameterBinding.ValueProperty,
							new ActivityBind(
								this.ClassName,
								string.IsNullOrEmpty(outvarname) ? wm.OutputBusinessObjectName : outvarname));
						lma.ParameterBindings.Add(wpb);
					}
					idesigner.Initialize(lma);
				}
			}
		}

		private void initLogicalInputActivity(IDesignerHost host, RepositoryService repSvc,
			TypeProvider typeProvider, Activity act, Deployment deployment)
		{
			LogicalInputActivity lia = (LogicalInputActivity)act;
			LogicalActivity la = repSvc.GetItem<LogicalActivity>(lia.LogicalActivityId);
			if ( lia is IncomingEvent && la == null ) {
				return;
			}
			if ( la == null && lia.LogicalActivityId > 0 ) {
				throw new Exception(string.Format("Unknown Error. Please recreate the activity '{0}' in the composite activity '{1}'.", act.Name, act.Parent.Name));
			}
			WorkflowEvent we = repSvc.GetItem<WorkflowEvent>(la.WorkflowEventID);
			if ( la != null && we != null ) {
				IDesigner idesigner = (IDesigner)host.GetDesigner(lia);
				if ( idesigner != null ) {
					setActivityProperty(lia, "InterfaceType",
						typeProvider.GetType(this.Namespace + "." + _ctdLocalInterface.Name));
					setActivityProperty(lia, "EventName", lia.LogicalActivityName);

					// check output variable name
					string varname = act.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
					if ( string.IsNullOrEmpty(varname) && we.BusinessObject != null ) {
						varname =
							string.Format("{0}_{1}", we.Name, we.BusinessObjectName);
						lia.SetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty, varname);
					} else if ( !string.IsNullOrEmpty(varname) && we.BusinessObject == null ) {
						varname = null;
						lia.SetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty, varname);
					}
					bool hasOutBO = we.BusinessObject != null;
					setActivityProperty(lia, "HasOutputObject", hasOutBO);
					Type type = null;
					if ( hasOutBO ) {
						MemberCreationService memberCreate = (MemberCreationService)this.GetService(typeof(IMemberCreationService));
						deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
											typeProvider, we.BusinessObject, this.GenerateDataContract);
						type = typeProvider.GetType(string.Format("{0}.{1}", this.NamespaceData, we.BusinessObject.Name));
						if ( la.OutputVariableName != varname ) {
							memberCreate.RemoveProperty(_workflow.ExtendedProperties.FullName,
														la.OutputVariableName,
														null);
						}
						memberCreate.CreateProperty(_workflow.ExtendedProperties.FullName,
													varname,
													type,
													null, true, false, false, null, false);
					}

					la.BeginEdit();
					la.WorkflowID = we.WorkflowID;
					la.OutputBusinessObjectID = we.BusinessObjectID;
					if ( hasOutBO ) {
						la.OutputVariableName = varname;
					}
					la.EndEdit(true);

					// add EventArgs property and assign to input property
					if ( type != null ) {
						string classEventArgsName = we.BusinessObjectName + Deployment.cExternalDataEventArgs;
						Type t = typeProvider.GetType(this.Namespace + "." + classEventArgsName);
						_memberCreation.CreatePropertyForWCFInputEventArgs(this.FullClassName,
							varname + Deployment.cExternalDataEventArgs,
							t,
							varname, PropertyNames.WorkflowInstanceId);
					}
					lia.ParameterBindings.Clear();
					WorkflowParameterBinding wpb;
					if ( we.BusinessObjectID > 0 ) {
						// add workflow instance parameter
						wpb = new WorkflowParameterBinding();
						wpb.ParameterName = "e";
						wpb.SetBinding(WorkflowParameterBinding.ValueProperty,
							new ActivityBind(this.ClassName, varname + Deployment.cExternalDataEventArgs));
						lia.ParameterBindings.Add(wpb);
					}
					idesigner.Initialize(lia);
				}
			}
		}
		#endregion

		#region Logical Activities Service Calls

		private CodeStatementCollection generateLogActCallbackServiceCall(LogicalAsyncStartActivity startAct, LogicalActivity startLogAct, CodeTypeReference typeRefSvcCalls)
		{
			CodeStatementCollection statements = new CodeStatementCollection();
			if ( startLogAct.LogicalMethod.IsAssignedTo == LogicalMethodAssignedTo.MessageQueue ) {
				statements.Add(
					new CodeVariableDeclarationStatement(
						typeRefSvcCalls, "sc",
						new CodeObjectCreateExpression(
							typeRefSvcCalls,
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(),
								"_orchestration"))));
				statements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(
								null,
								"_orchestration"),
							startLogAct.OutputVariableName),
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("sc"),
							string.Format("{0}Completed", startAct.Name))));
			} else {
				statements.Add(
					new CodeVariableDeclarationStatement(
						typeof(LogicalAsyncEndActivity),
						"endActivity",
						new CodeCastExpression(
							typeof(LogicalAsyncEndActivity),
							new CodeVariableReferenceExpression("activity"))));
				statements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(
								null,
								"_orchestration"),
							startAct.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string),
						new CodeCastExpression(
						string.Format("{0}.{1}", this.NamespaceData, startLogAct.OutputBusinessObject.Name),
							new CodePropertyReferenceExpression(
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression("endActivity"),
									"AsyncState"),
								"Output"))));
			}
			return statements;
		}

		private CodeStatementCollection generateLogActServiceCall(
			LogicalCapabilityActivity logcap, Repository.LogicalActivity logact, Repository.Operation op,
			Repository.Verb verb, Repository.WebService websvc, MessageQueueEx msmq,
			RepositoryBusinessRule endpointRule,
			List<LogicalRuleResultEPInfos> logRuleResultEPInfos,
			CodeTypeReference typeRefOutput, CodeTypeReference typeRefInput,
			CodeTypeReference typeRefSvcCalls)
		{
			CodeStatementCollection statements = new CodeStatementCollection();
			if ( logRuleResultEPInfos != null && logRuleResultEPInfos.Count > 0 ) {
				#region EPR
				// create service call for endpoint rule result:
				// ServiceCalls sc = new ServiceCalls(this._orchestration);
				// string result = OpenComposite.Orchestration.Rules.ENDPOINTRULE(_orchestration.VAR1, ...);
				// if ( result == "RESULT1" ) {
				//     [this._orchestration.OUTPUT1 = ]sc.InvokeABC_RESULT1([this._orchestration.INPUT1]);
				// } else if ( result == "RESULT2" ) {
				//     [this._orchestration.OUTPUT2 = ]sc.InvokeABC_RESULT2([this._orchestration.INPUT2]);
				// ...
				// } else if ( result = "RESULTn" ) {
				//     [this._orchestration.OUTPUTn = ]sc.InvokeABC_RESULTn([this._orchestration.INPUTn]);
				// }
				// create new ServiceCalls instance
				statements.Add(
					new CodeVariableDeclarationStatement(
						typeRefSvcCalls, "sc",
						new CodeObjectCreateExpression(
							typeRefSvcCalls,
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(),
								"_orchestration"))));
				// evaluate rule
				// string result = Rules.RULE_NAME(_orchestration.PARAM_1[,...]);
				List<CodeExpression> lstRuleParams = new List<CodeExpression>();
				foreach ( string paramname in endpointRule.GetParameters().Keys ) {
					lstRuleParams.Add(
						new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(),
								"_orchestration"),
							paramname));
				}
				CodeExpression rulesTargetObj =
					_workflow.IsConfigurable ?
					(CodeExpression)new CodePropertyReferenceExpression(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
						"Rules") :
					(CodeExpression)new CodeTypeReferenceExpression(this.NamespaceRules + ".Rules");
				CodeMethodInvokeExpression methinvoke = new CodeMethodInvokeExpression(
					rulesTargetObj,
					endpointRule.Name,
					lstRuleParams.ToArray());
				statements.Add(
					new CodeVariableDeclarationStatement(
						typeof(string), "result", methinvoke));
				CodeConditionStatement currentCondition = null;
				CodeConditionStatement firstCondition = null;
				CodeConditionStatement parentCondition = null;
				for ( int i = 0; i < logRuleResultEPInfos.Count; i++ ) {
					LogicalRuleResultEPInfos epinfos = logRuleResultEPInfos[i];
					currentCondition = new CodeConditionStatement();
					if ( firstCondition == null ) firstCondition = currentCondition;
					currentCondition.Condition =
						new CodeBinaryOperatorExpression(
							new CodeVariableReferenceExpression("result"),
							CodeBinaryOperatorType.IdentityEquality,
							new CodePrimitiveExpression(epinfos.RuleResultEndpoint.EndpointRuleResult));
					// create method invokation
					generateLogActServiceCallInvoke(
						Deployment.cServiceCallPrefix + logcap.LogicalActivityName +
							"_" + epinfos.RuleResultEndpoint.EndpointRuleResult,
						logcap, logact, op, verb,
						typeRefOutput, typeRefInput, currentCondition.TrueStatements);
					if ( parentCondition != null ) {
						parentCondition.FalseStatements.Add(currentCondition);
					}
					parentCondition = currentCondition;
				}
				if ( firstCondition != null ) statements.Add(firstCondition);
				#endregion
			} else if ( msmq != null ) {
				// create new ServiceCalls instance
				statements.Add(
					new CodeVariableDeclarationStatement(
						typeRefSvcCalls, "sc",
						new CodeObjectCreateExpression(
							typeRefSvcCalls,
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(),
								"_orchestration"))));
				// create method invokation
				generateLogActServiceCallInvoke(
					Deployment.cServiceCallPrefix + logcap.LogicalActivityName,
					logcap, logact, op, verb,
					typeRefOutput, typeRefInput, statements);
			} else if ( websvc != null ) {
				// create service call for single web service method call:
				// ServiceCalls sc = new ServiceCalls(this._orchestration);
				// [Orchestration.PROPERTY = ]ServiceCalls.LOGACTNAME([PARAMETER]);
				// create new ServiceCalls instance
				statements.Add(
					new CodeVariableDeclarationStatement(
						typeRefSvcCalls, "sc",
						new CodeObjectCreateExpression(
							typeRefSvcCalls,
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(),
								"_orchestration"))));
				// create method invokation
				generateLogActServiceCallInvoke(
					Deployment.cServiceCallPrefix + logcap.LogicalActivityName,
					logcap, logact, op, verb,
					typeRefOutput, typeRefInput, statements);
			}
			return statements;
		}


		private void generateLogActServiceCallInvoke(
			string methodName,
			LogicalCapabilityActivity logcap, Repository.LogicalActivity logact,
			Repository.Operation op, Repository.Verb verb,
			CodeTypeReference typeRefOutput, CodeTypeReference typeRefInput,
			CodeStatementCollection statements)
		{
			CodeMethodInvokeExpression methCallSvc =
					new CodeMethodInvokeExpression(
					new CodeMethodReferenceExpression(
						new CodeVariableReferenceExpression("sc"),
						methodName));
			methCallSvc.Parameters.Add(
				new CodeArgumentReferenceExpression("context"));
			NamedBusinessObjectCollection subscriptions = logact.GetSubscribedBusinessObjects();
			if ( subscriptions.Count > 0 ) {
				// input parameters
				foreach ( NamedBusinessObject item in subscriptions ) {
					string name = string.IsNullOrEmpty(item.Name) ? item.BusinessObject.Name : item.Name;
					methCallSvc.Parameters.Add(
						new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
								name + Deployment.cBObjPropSuffix));
				}
			} else if ( typeRefInput != null ) {
				// add single input parameter
				if ( logact != null && logact.InputBusinessObject != null ) {
				} else if ( op != null && string.IsNullOrEmpty(op.InputBusinessObjectName) ) {
					methCallSvc.Parameters.Add(
						new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
								op.InputBusinessObjectName + Deployment.cBObjPropSuffix));
				} else if ( verb != null && verb.InputBusinessObject != null ) {
					methCallSvc.Parameters.Add(
						new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
								verb.InputBusinessObject.Name + Deployment.cBObjPropSuffix));
				}
			}
			if ( typeRefOutput != null && !( logcap is LogicalAsyncStartActivity ) ) {
				// set return value to workflow parameter and
				// add method invocation to logical activity method
				if ( logact != null && logact.OutputBusinessObject != null ) {
					statements.Add(
						new CodeAssignStatement(
							new CodePropertyReferenceExpression(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
									logact.OutputVariableName + Deployment.cBObjPropSuffix),
							methCallSvc));
				} else if ( op != null && op.OutputBusinessObjectName != null ) {
					statements.Add(
						new CodeAssignStatement(
							new CodePropertyReferenceExpression(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), Deployment.cOrchestrationField),
									op.OutputBusinessObjectName + Deployment.cBObjPropSuffix),
							methCallSvc));
				}
			} else {
				// add method invocation to logical activity method (with no return value)
				statements.Add(methCallSvc);
			}
		}
		#endregion

		#region Generate Start/End Activities
		private void setASMXStartEnd(TypeProvider typeProvider, Repository.Operation op,
			CodeTypeReference typeRefOutput, CodeTypeReference typeRefInput, CodeMemberMethod meth)
		{
			IDesignerHost designerHost = GetService(typeof(IDesignerHost)) as IDesignerHost;
			SequenceActivity wfAct;
			if ( _workflow.Type == WorkflowType.Business_Process ) {
				wfAct = designerHost.RootComponent as HorizontalWorkflowActivity;
				return;
			} else
				wfAct = designerHost.RootComponent as SequentialWorkflowActivity;
			string boInName = "";
			string boOutName = "";
			if ( op != null ) {
				boInName = op.InputBusinessObjectName;
				boOutName = op.OutputBusinessObjectName;
			} else {
				if ( this.Workflow.InputBusinessObject != null )
					boInName = this.Workflow.InputBusinessObject.Name;
				if ( this.Workflow.OutputBusinessObject != null )
					boOutName = this.Workflow.OutputBusinessObject.Name;
			}
			if ( wfAct != null ) {
				DesignerTransaction trans = designerHost.CreateTransaction();
				WebServiceInputActivity actASMXIn;
				WebServiceOutputActivity actASMXOut;
				HandleExternalEventActivity actWCFInOld;
				CallExternalMethodActivity actWCFOutOld;
				LogicalInputActivity actWCFIn;
				LogicalMethodCallActivity actWCFOut;
				if ( meth == null ) {
					actASMXIn = null;
					actASMXOut = null;
					actWCFInOld = null;
					actWCFOutOld = null;
					actWCFIn = null;
					actWCFOut = null;
				} else {
					searchStartReplyActivities(wfAct, meth.Name,
						out actASMXIn, out actASMXOut,
						out actWCFInOld, out actWCFOutOld,
						out actWCFIn, out actWCFOut);
				}
				// delete wcf start / end activities
				removedisposeActivity(actWCFInOld);
				removedisposeActivity(actWCFOutOld);
				removedisposeActivity(actWCFIn);
				removedisposeActivity(actWCFOut);
				try {
					if ( meth != null ) {
						_memberCreation.RemoveProperty(this.FullClassName,
							PropertyNames.StartEventArgs,
							typeProvider.GetType(this.Namespace + "." + meth.Name + Deployment.cEventArgs));
						_memberCreation.RemoveField(this.FullClassName,
							PropertyNames.StartEventArgs + "Property");
					}
				} catch {
				}
				// create / config asmx start / end activities
				string actinname = null;
				string actoutname = null;
				if ( meth != null ) {
					if ( string.IsNullOrEmpty(_workflow.ExtendedProperties.StartActivityName) ) {
						actinname = meth.Name + Deployment.c_Start;
						_workflow.ExtendedProperties.StartActivityName = actinname;
					} else {
						actinname = _workflow.ExtendedProperties.StartActivityName;
					}
					if ( string.IsNullOrEmpty(_workflow.ExtendedProperties.EndActivityName) ) {
						actoutname = meth.Name + Deployment.c_Reply;
						_workflow.ExtendedProperties.EndActivityName = actoutname;
					} else {
						actoutname = _workflow.ExtendedProperties.EndActivityName;
					}
				}
				if ( actASMXIn == null ) {
					if ( typeRefInput != null ) {
						actASMXIn = designerHost.CreateComponent(typeof(WebServiceInputActivity), actinname)
									as WebServiceInputActivity;
						//actIn = new WebServiceInputActivity();
						actASMXIn.Name = actinname;
						actASMXIn.IsActivating = true;
						actASMXIn.InterfaceType =
							typeProvider.GetType(this.Namespace + "." + _ctdInterface.Name);
						actASMXIn.MethodName = meth.Name;

						actASMXIn.UserData.Add(Deployment.cOpenComposite, Deployment.cGenerated);
						ActivityBind actbindIn =
							new ActivityBind(this.ClassName, boInName + Deployment.cBObjPropSuffix);
						WorkflowParameterBinding wfparambindIn = new WorkflowParameterBinding("input");
						wfparambindIn.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindIn);

						actASMXIn.ParameterBindings.Add(wfparambindIn);
						( (IDesigner)designerHost.GetDesigner(actASMXIn) ).Initialize(actASMXIn);
						wfAct.Activities.Insert(0, actASMXIn);
					}
				} else {
					TypeDescriptor.GetProperties(actASMXIn)["InterfaceType"]
						.SetValue(actASMXIn, typeProvider.GetType(this.Namespace + "." + _ctdInterface.Name));
					TypeDescriptor.GetProperties(actASMXIn)["MethodName"]
						.SetValue(actASMXIn, meth.Name);
					actASMXIn.ParameterBindings.Clear();
					if ( typeRefInput != null ) {
						ActivityBind actbindIn =
							new ActivityBind(this.ClassName, boInName + Deployment.cBObjPropSuffix);
						WorkflowParameterBinding wfparambindIn = new WorkflowParameterBinding("input");
						wfparambindIn.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindIn);

						actASMXIn.ParameterBindings.Add(wfparambindIn);
						TypeDescriptor.Refresh(actASMXIn);
						( (IDesigner)designerHost.GetDesigner(actASMXIn) ).Initialize(actASMXIn);
					}
				}
				if ( actASMXOut == null && typeRefOutput != null ) {
					actASMXOut = designerHost.CreateComponent(typeof(WebServiceOutputActivity), actoutname)
								as WebServiceOutputActivity;
					actASMXOut.Name = actoutname;
					actASMXOut.InputActivityName = actinname;

					actASMXOut.UserData.Add(Deployment.cOpenComposite, Deployment.cGenerated);

					ActivityBind actbindOut =
						new ActivityBind(this.ClassName, boOutName + Deployment.cBObjPropSuffix);
					WorkflowParameterBinding wfparambindOut = new WorkflowParameterBinding("(ReturnValue)");
					wfparambindOut.SetBinding(
						System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
						actbindOut);

					actASMXOut.ParameterBindings.Add(wfparambindOut);
					( (IDesigner)designerHost.GetDesigner(actASMXOut) ).Initialize(actASMXOut);
					wfAct.Activities.Add(actASMXOut);
				} else if ( actASMXOut != null ) {
					actASMXOut.ParameterBindings.Clear();
					if ( typeRefOutput != null ) {
						ActivityBind actbindOut =
							new ActivityBind(this.ClassName, boOutName + Deployment.cBObjPropSuffix);
						WorkflowParameterBinding wfparambindOut = new WorkflowParameterBinding("(ReturnValue)");
						wfparambindOut.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindOut);

						actASMXOut.ParameterBindings.Add(wfparambindOut);
						( (IDesigner)designerHost.GetDesigner(actASMXOut) ).Initialize(actASMXOut);
					}
				}
				trans.Commit();
			}
			AddObjectGraphToDesignerHost(designerHost, wfAct);
		}

		private void removedisposeActivity(Activity act)
		{
			try {
				if ( act != null ) {
					act.Parent.Activities.Remove(act);
					act.Dispose();
					act = null;
				}
			} catch { }
		}

		private void setWCFStartEnd(TypeProvider typeProvider, Repository.Operation op,
			CodeTypeReference typeRefOutput, CodeTypeReference typeRefInput, CodeMemberMethod meth)
		{
			IDesignerHost designerHost = GetService(typeof(IDesignerHost)) as IDesignerHost;
			SequenceActivity wfAct;
			if ( _workflow.Type == WorkflowType.Business_Process )
				wfAct = designerHost.RootComponent as HorizontalWorkflowActivity;
			else
				wfAct = designerHost.RootComponent as SequentialWorkflowActivity;
			string boInName = "";
			string boOutName = "";
			if ( op != null ) {
				boInName = op.InputBusinessObjectName;
				boOutName = op.OutputBusinessObjectName;
			} else {
				if ( this.Workflow.InputBusinessObject != null )
					boInName = this.Workflow.InputBusinessObject.Name;
				if ( this.Workflow.OutputBusinessObject != null )
					boOutName = this.Workflow.OutputBusinessObject.Name;
			}
			if ( wfAct != null ) {
				DesignerTransaction trans = designerHost.CreateTransaction();
				try {
					WebServiceInputActivity actASMXIn;
					WebServiceOutputActivity actASMXOut;
					HandleExternalEventActivity actWCFInOld;
					CallExternalMethodActivity actWCFOutOld;
					LogicalInputActivity actWCFIn;
					LogicalMethodCallActivity actWCFOut;
					if ( meth != null ) {
						searchStartReplyActivities(wfAct, meth.Name,
							out actASMXIn, out actASMXOut,
							out actWCFInOld, out actWCFOutOld,
							out actWCFIn, out actWCFOut);
					} else {
						actASMXIn = null;
						actASMXOut = null;
						actWCFInOld = null;
						actWCFOutOld = null;
						actWCFIn = null;
						actWCFOut = null;
					}
					// delete asmx start / end activities
					removedisposeActivity(actASMXIn);
					removedisposeActivity(actASMXOut);
					removedisposeActivity(actWCFInOld);
					removedisposeActivity(actWCFOutOld);
					// create / config wcf start / end activities
					if ( typeRefInput != null ) {
						// create workflowInstanceId Property
						_memberCreation.CreateProperty(this.FullClassName,
													   PropertyNames.WorkflowInstanceId,
													   typeof(Guid),
													   null,
													   true,
													   false,
													   false,
													   null,
													   false);

						// add EventArgs property and assign to input property
						_memberCreation.CreatePropertyForWCFInputEventArgs(this.FullClassName,
							PropertyNames.StartEventArgs,
							typeProvider.GetType(this.Namespace + "." + meth.Name + Deployment.cEventArgs),
							boInName, PropertyNames.WorkflowInstanceId);
					}
					string actinname = null;
					string actoutname = null;
					if ( meth != null ) {
						if ( string.IsNullOrEmpty(_workflow.ExtendedProperties.StartActivityName) ) {
							actinname = meth.Name + Deployment.c_Start;
							_workflow.ExtendedProperties.StartActivityName = actinname;
						} else {
							actinname = _workflow.ExtendedProperties.StartActivityName;
						}
						if ( string.IsNullOrEmpty(_workflow.ExtendedProperties.EndActivityName) ) {
							actoutname = meth.Name + Deployment.c_Reply;
							_workflow.ExtendedProperties.EndActivityName = actoutname;
						} else {
							actoutname = _workflow.ExtendedProperties.EndActivityName;
						}
					}
					if ( actWCFIn == null ) {
						if ( typeRefInput != null ) {
							actWCFIn = designerHost.CreateComponent(typeof(LogicalInputActivity), actinname)
										as LogicalInputActivity;
							actWCFIn.Name = actinname;
							actWCFIn.InterfaceType =
								typeProvider.GetType(this.Namespace + "." + _ctdLocalInterface.Name);
							actWCFIn.EventName = meth.Name;

							actWCFIn.UserData.Add(Deployment.cOpenComposite, Deployment.cGenerated);
							ActivityBind actbindIn =
								new ActivityBind(this.ClassName, PropertyNames.StartEventArgs);
							WorkflowParameterBinding wfparambindIn = new WorkflowParameterBinding("e");
							wfparambindIn.SetBinding(
								System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
								actbindIn);

							actWCFIn.ParameterBindings.Add(wfparambindIn);
							( (IDesigner)designerHost.GetDesigner(actWCFIn) ).Initialize(actWCFIn);
							wfAct.Activities.Insert(0, actWCFIn);
						}
					} else {
						setActivityProperty(actWCFIn, "InterfaceType",
							typeProvider.GetType(this.Namespace + "." + _ctdLocalInterface.Name));
						setActivityProperty(actWCFIn, "EventName", meth.Name);
						ActivityBind actbindIn =
							new ActivityBind(this.ClassName, PropertyNames.StartEventArgs);
						WorkflowParameterBinding wfparambindIn = new WorkflowParameterBinding("e");
						wfparambindIn.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindIn);

						actWCFIn.ParameterBindings.Add(wfparambindIn);
					}

					if ( actWCFOut == null && typeRefOutput != null ) {
						actWCFOut = designerHost.CreateComponent(typeof(LogicalMethodCallActivity), actoutname)
									as LogicalMethodCallActivity;
						actWCFOut.Name = actoutname;
						actWCFOut.InterfaceType =
							typeProvider.GetType(this.Namespace + "." + _ctdLocalInterface.Name);
						actWCFOut.MethodName = actoutname;

						actWCFOut.UserData.Add(Deployment.cOpenComposite, Deployment.cGenerated);

						ActivityBind actbindOut =
							new ActivityBind(this.ClassName, boOutName + Deployment.cBObjPropSuffix);
						WorkflowParameterBinding wfparambindOut = new WorkflowParameterBinding("output");
						wfparambindOut.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindOut);

						ActivityBind actbindWInstId =
							new ActivityBind(this.ClassName, PropertyNames.WorkflowInstanceId);
						WorkflowParameterBinding wfparambindWInstId =
							new WorkflowParameterBinding("workflowInstanceId");
						wfparambindWInstId.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindWInstId);

						actWCFOut.ParameterBindings.Add(wfparambindOut);
						actWCFOut.ParameterBindings.Add(wfparambindWInstId);
						( (IDesigner)designerHost.GetDesigner(actWCFOut) ).Initialize(actWCFOut);
						wfAct.Activities.Add(actWCFOut);
					} else if ( actWCFOut != null ) {
						setActivityProperty(actWCFOut, "InterfaceType",
							typeProvider.GetType(this.Namespace + "." + _ctdLocalInterface.Name));
						setActivityProperty(actWCFOut, "MethodName", actoutname);

						ActivityBind actbindOut =
							new ActivityBind(this.ClassName, boOutName + Deployment.cBObjPropSuffix);
						WorkflowParameterBinding wfparambindOut = new WorkflowParameterBinding("output");
						wfparambindOut.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindOut);

						ActivityBind actbindWInstId =
							new ActivityBind(this.ClassName, PropertyNames.WorkflowInstanceId);
						WorkflowParameterBinding wfparambindWInstId =
							new WorkflowParameterBinding("workflowInstanceId");
						wfparambindWInstId.SetBinding(
							System.Workflow.ComponentModel.WorkflowParameterBinding.ValueProperty,
							actbindWInstId);

						actWCFOut.ParameterBindings.Add(wfparambindOut);
						actWCFOut.ParameterBindings.Add(wfparambindWInstId);
					}
				} catch {
					trans.Cancel();
					trans = null;
				} finally {
					if ( trans != null ) trans.Commit();
				}
			}
			AddObjectGraphToDesignerHost(designerHost, wfAct);
		}
		private void searchStartReplyActivities(SequenceActivity wfAct, string methodName,
												out WebServiceInputActivity actASMXIn,
												out WebServiceOutputActivity actASMXOut,
												out HandleExternalEventActivity actWCFInOld,
												out CallExternalMethodActivity actWCFOutOld,
												out LogicalInputActivity actWCFIn,
												out LogicalMethodCallActivity actWCFOut)
		{
			string actinname = null;
			string actoutname = null;
			if ( string.IsNullOrEmpty(_workflow.ExtendedProperties.StartActivityName) ) {
				actinname = methodName + Deployment.c_Start;
				_workflow.ExtendedProperties.StartActivityName = actinname;
			} else {
				actinname = _workflow.ExtendedProperties.StartActivityName;
			}
			if ( string.IsNullOrEmpty(_workflow.ExtendedProperties.EndActivityName) ) {
				actoutname = methodName + Deployment.c_Reply;
				_workflow.ExtendedProperties.EndActivityName = actoutname;
			} else {
				actoutname = _workflow.ExtendedProperties.EndActivityName;
			}
			actASMXIn = wfAct.Activities.Find(
				delegate(Activity a)
				{
					WebServiceInputActivity act = a as WebServiceInputActivity;
					return ( act != null && act.Name == actinname );
				}) as WebServiceInputActivity;
			actASMXOut = wfAct.Activities.Find(
				delegate(Activity a)
				{
					WebServiceOutputActivity act = a as WebServiceOutputActivity;
					return ( act != null && act.Name == actoutname );
				}) as WebServiceOutputActivity;
			actWCFInOld = wfAct.Activities.Find(
				delegate(Activity a)
				{
					HandleExternalEventActivity act = a as HandleExternalEventActivity;
					return ( act != null && act.Name == actinname );
				}) as HandleExternalEventActivity;
			actWCFOutOld = wfAct.Activities.Find(
				delegate(Activity a)
				{
					CallExternalMethodActivity act = a as CallExternalMethodActivity;
					return ( act != null && act.Name == actoutname );
				}) as CallExternalMethodActivity;
			actWCFIn = wfAct.Activities.Find(
				delegate(Activity a)
				{
					LogicalInputActivity act = a as LogicalInputActivity;
					return ( act != null && act.Name == actinname );
				}) as LogicalInputActivity;
			actWCFOut = wfAct.Activities.Find(
				delegate(Activity a)
				{
					LogicalMethodCallActivity act = a as LogicalMethodCallActivity;
					return ( act != null && act.Name == actoutname );
				}) as LogicalMethodCallActivity;
		}
		#endregion

		#region Rules
		private RuleDefinitions getRuleDefinitions()
		{
			RuleDefinitions ruleDef = null;
			using ( TextReader tr = this.GetFileReader(".rules") )
			using ( XmlTextReader xtr = new XmlTextReader(tr) ) {
				if ( tr == null ) {
					ruleDef = new RuleDefinitions();
				} else {
					WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
					ruleDef = serializer.Deserialize(xtr) as RuleDefinitions;
				}
			}
			return ruleDef;
		}
		private void setRuleDefinitions(RuleDefinitions ruleDef)
		{
			using ( TextWriter tw = this.GetFileWriter(".rules") )
			using ( XmlTextWriter xtw = new XmlTextWriter(tw) ) {
				WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
				serializer.Serialize(xtw, ruleDef);
			}
		}

		private bool existsRuleParameterResolve(KeyValuePair<string, string> item)
		{
			bool paramexists = _workflow.ExtendedProperties.WorkflowVariables.Exists(
				delegate(Repository.Workflow.RuleParameterResolve rpr)
				{
					return ( rpr.ParameterName == item.Key );
				});
			return paramexists;
		}
		private static bool existsNounInResolveList(BindingListEx<Repository.Workflow.RuleParameterResolve> lst, int id)
		{
			return lst.Exists(delegate(Repository.Workflow.RuleParameterResolve rpr)
			{
				return ( rpr.ParameterID == id );
			});
		}
		private static Repository.Workflow.RuleParameterResolve getRPRByName(
			BindingListEx<Repository.Workflow.RuleParameterResolve> lst, string name)
		{
			return lst.Find(delegate(Repository.Workflow.RuleParameterResolve rpr)
			{
				return ( rpr.ParameterName == name );
			});
		}
		#endregion

		#region Mashup
		private void generateMashupForm()
		{

		}
		#endregion

		#region participant rule methods
		private CodeExpression createParticipantRuleCall(RepositoryBusinessRule partrule)
		{
			//List<CodeExpression> lstRuleParams = new List<CodeExpression>();
			//Dictionary<OpenComposite.EII.Repository.Workflow.RuleParameterResolve, CodeExpression> dicParams =
			//    frm.GetRuleParameterResolutionExpression();
			//foreach ( KeyValuePair<OpenComposite.EII.Repository.Workflow.RuleParameterResolve, CodeExpression> val
			//    in dicParams ) {
			//    memberCreation.CreatePropertyForRuleParameterResolution(
			//        _loader.FullClassName, val.Key.ParameterName,
			//        OpenComposite.EII.Helpers.GetDotNetTypeOfDataTypeString(val.Key.ParameterDataType),
			//        val.Value);
			//    lstRuleParams.Add(
			//        new CodePropertyReferenceExpression(
			//            new CodeThisReferenceExpression(),
			//            val.Key.ParameterName));
			//    if ( !_loader.Workflow.ExtendedProperties.WorkflowVariables.Contains(val.Key) )
			//        _loader.Workflow.ExtendedProperties.WorkflowVariables.Add(val.Key);
			//}
			//#region check that all workflow variables used in rules
			//List<string> lstVarNms = new List<string>();
			//foreach ( RepositoryBusinessRule rule in _loader.Workflow.GetRules() ) {
			//    Dictionary<string, string> parameters = rule.GetParameters();
			//    lstVarNms.AddRange(parameters.Keys);
			//}
			//Repository.Workflow.RuleParameterResolve[] rprs =
			//    _loader.Workflow.ExtendedProperties.WorkflowVariables.ToArray();
			//foreach ( Repository.Workflow.RuleParameterResolve rpr in rprs ) {
			//    if ( !lstVarNms.Contains(rpr.ParameterName) )
			//        _loader.Workflow.ExtendedProperties.WorkflowVariables.Remove(rpr);
			//}
			//#endregion
			//RuleDefinitions ruleDef = getRuleDefinitions();
			//if ( !ruleDef.Conditions.Contains(frm.SelectedBusinessRule.Name) ) {
			//    ruleDef.Conditions.Add(
			//        new RuleExpressionCondition(
			//            frm.SelectedBusinessRule.Name,
			//            new CodeBinaryOperatorExpression(
			//                frm.GetRuleInvokationExpression(lstRuleParams),
			//                CodeBinaryOperatorType.ValueEquality,
			//                new CodePrimitiveExpression(frm.SelectedResult))));
			//    setRuleDefinitions(ruleDef);
			//} else {
			//    ( (RuleExpressionCondition)ruleDef.Conditions[frm.SelectedBusinessRule.Name] ).Expression =
			//            new CodeBinaryOperatorExpression(
			//                frm.GetRuleInvokationExpression(lstRuleParams),
			//                CodeBinaryOperatorType.ValueEquality,
			//                new CodePrimitiveExpression(frm.SelectedResult));
			//    setRuleDefinitions(ruleDef);
			//}
			return null;
		}
		public Dictionary<OpenComposite.EII.Repository.Workflow.RuleParameterResolve, CodeExpression>
			GetRuleParameterResolutionExpression()
		{
			//Dictionary<OpenComposite.EII.Repository.Workflow.RuleParameterResolve, CodeExpression> dicParams =
			//    new Dictionary<OpenComposite.EII.Repository.Workflow.RuleParameterResolve, CodeExpression>();

			//foreach ( Repository.Workflow.RuleParameterResolve rpr in _listResolve ) {
			//    dicParams.Add(rpr, null);
			//}

			//return dicParams;
			return null;
		}
		private void fillParameterResolve()
		{
			//if ( _listResolve == null ) {
			//    _listResolve = new List<OpenComposite.EII.Repository.Workflow.RuleParameterResolve>();
			//} else {
			//    _listResolve.Clear();
			//}
			////ruleParameterResolveListBindingSource.Clear();
			//string[] strsParams = _brule.Parameters.Split(';');
			//foreach ( string sParam in strsParams ) {
			//    string[] p = sParam.Split(':');
			//    OpenComposite.EII.Repository.Workflow.RuleParameterResolve rpr =
			//        new OpenComposite.EII.Repository.Workflow.RuleParameterResolve();
			//    if ( p.Length > 0 )
			//        rpr.ParameterName = p[0];
			//    if ( p.Length > 1 )
			//        rpr.ParameterDataType = p[1];
			//    //ruleParameterResolveListBindingSource.Add(rpr);
			//    _listResolve.Add(rpr);
			//}
		}

		#endregion

		#region Generate IO Types

		private void getGeneratedIOTypesOfOperation(TypeProvider typeProvider,
			Repository.Operation op, out CodeTypeReference typeRefOutput, out CodeTypeReference typeRefInput)
		{
			typeRefOutput = null;
			typeRefInput = null;

			if ( op.OutputSchema != null && !string.IsNullOrEmpty(op.OutputBusinessObjectName) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + op.OutputBusinessObjectName);
				if ( t == null )
					throw new InvalidOperationException("The output business object \"" + op.OutputBusinessObjectName + "\" does not exists in the current process.");

				typeRefOutput = new CodeTypeReference(t);
				if ( typeRefOutput == null )
					throw new InvalidOperationException("The output business object \"" + op.OutputBusinessObjectName + "\" does not exists in the current process.");
			}
			if ( op.InputSchema != null && !string.IsNullOrEmpty(op.InputBusinessObjectName) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + op.InputBusinessObjectName);
				if ( t == null )
					throw new InvalidOperationException("The input business object \"" + op.InputBusinessObjectName + "\" does not exists in the current process.");

				typeRefInput = new CodeTypeReference(t);
				if ( typeRefInput == null )
					throw new InvalidOperationException("The input business object \"" + op.InputBusinessObjectName + "\" does not exists in the current process.");
			}

		}
		private void getGeneratedIOTypesOfLogicalActivity(TypeProvider typeProvider,
			Repository.LogicalActivity logact, out CodeTypeReference typeRefOutput, out CodeTypeReference typeRefInput)
		{
			typeRefOutput = null;
			typeRefInput = null;

			if ( logact.HasOutputBusinessObject ) {
				string outboname = logact.OutputBusinessObject.Name;
				Type t = typeProvider.GetType(this.NamespaceData + "." + outboname);
				if ( t == null )
					throw new InvalidOperationException("The output business object \"" + outboname +
														"\" does not exists in the current process.");

				typeRefOutput = new CodeTypeReference(t);
				if ( typeRefOutput == null )
					throw new InvalidOperationException("The output business object \"" + outboname +
														"\" does not exists in the current process.");
			}
			if ( logact.HasInputBusinessObject ) {
				string inboname = logact.InputBusinessObject.Name;
				Type t = typeProvider.GetType(this.NamespaceData + "." + inboname);
				if ( t == null )
					throw new InvalidOperationException("The input business object \"" + inboname +
														"\" does not exists in the current process.");

				typeRefInput = new CodeTypeReference(t);
				if ( typeRefInput == null )
					throw new InvalidOperationException("The input business object \"" + inboname +
														"\" does not exists in the current process.");
			}

		}
		private void getGeneratedIOTypesOfLogicalActivity(TypeProvider typeProvider,
			OpenComposite.EII.Repository.LogicalActivity logact,
			out CodeTypeReference typeRefOutput, ref List<CodeTypeReference> listTypeRefInputLogAct)
		{
			typeRefOutput = null;

			if ( logact.HasOutputBusinessObject ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + logact.OutputBusinessObject.Name);
				if ( t == null )
					throw new InvalidOperationException("The Business Object \"" + logact.OutputBusinessObject.Name + "\" does not exists in the current process.");
				typeRefOutput = new CodeTypeReference(t);
			}
			NamedBusinessObjectCollection bos = logact.GetSubscribedBusinessObjects();
			if ( bos != null ) {
				foreach ( NamedBusinessObject item in bos ) {
					Type t = null;
					if ( item.BusinessObject.WorkflowFieldID > 0 ) {
						if ( item.BusinessObject.WorkflowField.BusinessObjectID > 0 ) {
							t = typeProvider.GetType(this.NamespaceData + "." + item.BusinessObject.WorkflowField.BusinessObject.Name);
						} else {
							t = Global.Data.GetDOTNETTypeofXSDDataType(item.BusinessObject.WorkflowField.DataType);
						}
					} else {
						t = typeProvider.GetType(this.NamespaceData + "." + item.BusinessObject.Name);
					}
					if ( t != null ) {
						CodeTypeReference ctr = new CodeTypeReference(t);
						ctr.UserData.Add("BusinessObject", item);
						listTypeRefInputLogAct.Add(ctr);
					}
				}
			}
		}
		private void getGeneratedIOTypesOfOperation(TypeProvider typeProvider,
			Repository.Verb verb, out CodeTypeReference typeRefOutput, out CodeTypeReference typeRefInput)
		{
			typeRefOutput = null;
			typeRefInput = null;

			if ( verb.OutputBusinessObjectID > 0 && !string.IsNullOrEmpty(verb.OutputBusinessObjectName) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + verb.OutputBusinessObjectName);
				if ( t == null )
					throw new InvalidOperationException("The output business object \"" + verb.OutputBusinessObjectName + "\" does not exists in the current process.");

				typeRefOutput = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + verb.OutputBusinessObjectName));
				//typeRefOutput = importer.GetCodeTypeReference(
				//    new XmlQualifiedName(op.OutputBusinessObjectName, op.OutputSchema.TargetNamespace));
				if ( typeRefOutput == null )
					throw new InvalidOperationException("The output business object \"" + verb.OutputBusinessObjectName + "\" does not exists in the current process.");
			}
			if ( verb.InputBusinessObjectID > 0 && !string.IsNullOrEmpty(verb.InputBusinessObjectName) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + verb.InputBusinessObjectName);
				if ( t == null )
					throw new InvalidOperationException("The input business object \"" + verb.InputBusinessObjectName + "\" does not exists in the current process.");

				typeRefInput = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + verb.InputBusinessObjectName));
				//typeRefInput = importer.GetCodeTypeReference(
				//    new XmlQualifiedName(op.InputBusinessObjectName, op.InputSchema.TargetNamespace));
				if ( typeRefInput == null )
					throw new InvalidOperationException("The input business object \"" + verb.InputBusinessObjectName + "\" does not exists in the current process.");
			}

		}
		private void getGeneratedIOTypesOfWorkflow(TypeProvider typeProvider,
			Repository.Workflow wf, out CodeTypeReference typeRefOutput, out CodeTypeReference typeRefInput)
		{
			typeRefOutput = null;
			typeRefInput = null;

			if ( wf.OutputBusinessObjectID > 0 && !string.IsNullOrEmpty(wf.OutputBusinessObject.Name) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + wf.OutputBusinessObject.Name);
				if ( t == null )
					throw new InvalidOperationException("The output business object \"" + wf.OutputBusinessObject.Name + "\" does not exists in the current process.");

				typeRefOutput = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + wf.OutputBusinessObject.Name));
				//typeRefOutput = importer.GetCodeTypeReference(
				//    new XmlQualifiedName(op.OutputBusinessObjectName, op.OutputSchema.TargetNamespace));
				if ( typeRefOutput == null )
					throw new InvalidOperationException("The output business object \"" + wf.OutputBusinessObject.Name + "\" does not exists in the current process.");
			}
			if ( wf.InputBusinessObjectID > 0 && !string.IsNullOrEmpty(wf.InputBusinessObject.Name) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + wf.InputBusinessObject.Name);
				if ( t == null )
					throw new InvalidOperationException("The input business object \"" + wf.InputBusinessObject.Name + "\" does not exists in the current process.");

				typeRefInput = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + wf.InputBusinessObject.Name));
				//typeRefInput = importer.GetCodeTypeReference(
				//    new XmlQualifiedName(op.InputBusinessObjectName, op.InputSchema.TargetNamespace));
				if ( typeRefInput == null )
					throw new InvalidOperationException("The input business object \"" + wf.InputBusinessObject.Name + "\" does not exists in the current process.");
			}

		}
		private void getGeneratedIOTypesOfOperation(TypeProvider typeProvider,
			OpenComposite.EII.Repository.Operation op, Repository.BusinessObject[] subscribedBOs,
			out CodeTypeReference typeRefOutput, ref List<CodeTypeReference> listTypeRefInputLogAct)
		{
			typeRefOutput = null;

			if ( op.OutputSchema != null && !string.IsNullOrEmpty(op.OutputBusinessObjectName) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + op.OutputBusinessObjectName);
				if ( t == null )
					throw new InvalidOperationException("The Business Object \"" + op.OutputBusinessObjectName + "\" does not exists in the current process.");
				typeRefOutput = new CodeTypeReference(t);
			}
			foreach ( Repository.BusinessObject bo in subscribedBOs ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + bo.Name);
				if ( t != null ) {
					listTypeRefInputLogAct.Add(new CodeTypeReference(t));
					//throw new InvalidOperationException("The Business Object \"" + bo.Name + "\" does not exists in the current process.");
				}
			}
		}
		private void getGeneratedIOTypesOfOperation(TypeProvider typeProvider,
			OpenComposite.EII.Repository.Verb verb, Repository.BusinessObject[] subscribedBOs,
			out CodeTypeReference typeRefOutput, ref List<CodeTypeReference> listTypeRefInputLogAct)
		{
			typeRefOutput = null;

			if ( verb.OutputBusinessObjectID > 0 && !string.IsNullOrEmpty(verb.OutputBusinessObjectName) ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + verb.OutputBusinessObjectName);
				if ( t == null )
					throw new InvalidOperationException("The Business Object \"" + verb.OutputBusinessObjectName + "\" does not exists in the current process.");
				typeRefOutput = new CodeTypeReference(t);
				if ( typeRefOutput == null )
					throw new InvalidOperationException("The Business Object \"" + verb.OutputBusinessObjectName + "\" does not exists in the current process.");
			}
			foreach ( Repository.BusinessObject bo in subscribedBOs ) {
				Type t = typeProvider.GetType(this.NamespaceData + "." + bo.Name);
				if ( t != null ) {
					listTypeRefInputLogAct.Add(new CodeTypeReference(t));
					//throw new InvalidOperationException("The Business Object \"" + bo.Name + "\" does not exists in the current process.");
				}
			}
		}

		private void getGeneratedIOTypesOfDataAggregation(TypeProvider typeProvider,
			OpenComposite.EII.Repository.BusinessObject boOutput, Repository.LogicalActivity logact,
			out CodeTypeReference typeRefOutput, ref List<CodeTypeReference> listTypeRefInput)
		{
			typeRefOutput = null;

			if ( boOutput.Schema != null && !string.IsNullOrEmpty(boOutput.Name) ) {
				typeRefOutput = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + boOutput.Name));
				if ( typeRefOutput == null )
					throw new Exception("Unknown Output TypeReference.");
			}
			RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");
			NamedBusinessObjectCollection subscribedBOs = logact.GetSubscribedBusinessObjects();
			foreach ( NamedBusinessObject item in subscribedBOs ) {
				Type type = null;
				if ( item.BusinessObject.WorkflowFieldID > 0 ) {
					if ( item.BusinessObject.WorkflowField.BusinessObjectID > 0 ) {
						type = typeProvider.GetType(this.NamespaceData + "." + item.BusinessObject.WorkflowField.BusinessObject.Name);
					} else {
						type = Global.Data.GetDOTNETTypeofXSDDataType(item.BusinessObject.WorkflowField.DataType);
					}
				} else {
					type = typeProvider.GetType(this.NamespaceData + "." + item.BusinessObject.Name);
				}
				if ( type == null ) {
					throw new Exception(
						string.Format("The Business Object '{0}' is not available for the Activity '{1}'.",
							item.BusinessObject.Name, logact.Name));
				}
				CodeTypeReference ctr = new CodeTypeReference(type);
				ctr.UserData.Add("BusinessObject", item);
				listTypeRefInput.Add(ctr);
			}
		}

		#endregion

		#region Local Service Interface and Implementation

		private void generateLocalService()
		{
			string startOpName = null;
			CodeTypeReference typeRefInput = null;
			CodeTypeReference typeRefOutput = null;
			CodeNamespace nsLocalSvc = _codeLocalService.Namespaces[0];

			#region get start operation informations
			TypeProvider typeProvider = (TypeProvider)GetService(typeof(ITypeProvider));

			Repository.Operation op = null;
			BindingListEx<Repository.Operation> ops =
				Global.Data.GetWorkflowOperation(_workflow.ID);
			if ( ops.Count <= 0 ) {
				if ( this._workflow.Type != OpenComposite.EII.Repository.WorkflowType.Business_Process )
					throw new Exception("No orchestration start operation exists.");
			} else {
				op = ops[0];
			}
			if ( op != null ) {
				startOpName = op.Name;
				getGeneratedIOTypesOfOperation(typeProvider, op, out typeRefOutput, out typeRefInput);
			} else if ( !string.IsNullOrEmpty(this.Workflow.StartName) ) {
				startOpName = this.Workflow.StartName;
				getGeneratedIOTypesOfWorkflow(typeProvider, this.Workflow, out typeRefOutput, out typeRefInput);
			}
			if ( string.IsNullOrEmpty(startOpName) ) {
				Debug.WriteLine("No start operation available.");
				return;
			}
			#endregion

			generateLocalSvcInterface(nsLocalSvc, typeRefInput, typeRefOutput, startOpName);
			generateLocalSvcClass(nsLocalSvc, typeRefInput, typeRefOutput, startOpName);

			refreshTypeProvider(ref typeProvider, ref _codeLocalService);
		}

		private void generateLocalSvcInterface(CodeNamespace nsLocalSvc,
			CodeTypeReference typeRefInput, CodeTypeReference typeRefOutput, string startOpName)
		{
			#region add ExternalDataEventArgs class for start event
			CodeTypeDeclaration ctdEventArgs = new CodeTypeDeclaration(startOpName + Deployment.cEventArgs);
			ctdEventArgs.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			//	add SerializableAttribute
			ctdEventArgs.CustomAttributes.Add(
				new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
			//	add Base Class
			ctdEventArgs.BaseTypes.Add(typeof(ExternalDataEventArgs));
			//	add Constuctor
			CodeConstructor ctorEventArgs = new CodeConstructor();
			ctorEventArgs.Attributes = MemberAttributes.Final | MemberAttributes.Public;
			ctorEventArgs.Parameters.Add(	// XEventArgs(Guid instanceId, ...)
				new CodeParameterDeclarationExpression(typeof(Guid), "instanceId"));
			//			: base(instanceId);
			ctorEventArgs.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("instanceId"));
			if ( typeRefInput != null ) {
				ctorEventArgs.Parameters.Add(	// XEventArgs(..., InputType input)
					new CodeParameterDeclarationExpression(typeRefInput, "input"));
				ctorEventArgs.Statements.Add(	// _input = input;
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_input"),
						new CodeArgumentReferenceExpression("input")));
			}
			ctdEventArgs.Members.Add(ctorEventArgs);
			if ( typeRefInput != null ) {
				//	add private input data field
				ctdEventArgs.Members.Add(
					new CodeMemberField(typeRefInput, "_input"));
				//	add public input data property (get)
				CodeMemberProperty propInput = new CodeMemberProperty();
				propInput.Name = "Input";
				propInput.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				propInput.Type = typeRefInput;
				propInput.HasGet = true;
				propInput.HasSet = false;
				propInput.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_input")));

				ctdEventArgs.Members.Add(propInput);
			}
			// add EventArgs class to namespace
			nsLocalSvc.Types.Add(ctdEventArgs);
			#endregion

			#region add start event handler delegate
			// public delegate void XEventHandler(object sender, XEventArgs e);
			CodeTypeDelegate delegateEvent = new CodeTypeDelegate();
			delegateEvent.Name = startOpName + Deployment.cEventHandler;
			delegateEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			delegateEvent.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(object), "sender"));
			delegateEvent.Parameters.Add(
				new CodeParameterDeclarationExpression(ctdEventArgs.Name, "e"));
			// add delegate to namespace
			nsLocalSvc.Types.Add(delegateEvent);
			#endregion

			if ( typeRefOutput != null ) {
				#region add ReplyEventArgs class for reply method
				CodeTypeDeclaration ctdEAReply = new CodeTypeDeclaration();
				ctdEAReply.Name = startOpName + Deployment.c_Reply + Deployment.cEventArgs;
				//	add SerializableAttribute
				ctdEAReply.CustomAttributes.Add(
					new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
				//	add Base Class
				ctdEAReply.BaseTypes.Add(typeof(EventArgs));
				//	add Constuctor
				CodeConstructor ctorEAReply = new CodeConstructor();
				ctorEAReply.Attributes = MemberAttributes.Final | MemberAttributes.Public;
				ctorEAReply.Parameters.Add(	// X_ReplyEventArgs(Guid instanceId, ...)
					new CodeParameterDeclarationExpression(typeof(Guid), "instanceId"));
				ctorEAReply.Parameters.Add(	// X_ReplyEventArgs(..., OutputType output)
					new CodeParameterDeclarationExpression(typeRefOutput, "output"));
				ctorEAReply.Statements.Add(	// _instanceId = instanceId
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_instanceId"),
						new CodeArgumentReferenceExpression("instanceId")));
				ctorEAReply.Statements.Add(	// _output = output;
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_output"),
						new CodeArgumentReferenceExpression("output")));
				ctdEAReply.Members.Add(ctorEAReply);

				//	add private data fields
				ctdEAReply.Members.Add(
					new CodeMemberField(typeof(Guid), "_instanceId"));
				ctdEAReply.Members.Add(
					new CodeMemberField(typeRefOutput, "_output"));
				//	add public data properties (get)
				CodeMemberProperty propInstanceID = new CodeMemberProperty();
				propInstanceID.Name = "InstanceId";
				propInstanceID.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				propInstanceID.Type = new CodeTypeReference(typeof(Guid));
				propInstanceID.HasGet = true;
				propInstanceID.HasSet = false;
				propInstanceID.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_instanceId")));
				CodeMemberProperty propOutput = new CodeMemberProperty();
				propOutput.Name = "Output";
				propOutput.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				propOutput.Type = typeRefOutput;
				propOutput.HasGet = true;
				propOutput.HasSet = false;
				propOutput.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_output")));

				ctdEAReply.Members.Add(propInstanceID);
				ctdEAReply.Members.Add(propOutput);
				// add ReplyEventArgs class to namespace
				nsLocalSvc.Types.Add(ctdEAReply);
				#endregion

				#region add reply event handler delegate
				// public delegate void X_ReplyEventHandler(object sender, X_ReplyEventArgs e);
				CodeTypeDelegate delegateReplyEvent = new CodeTypeDelegate();
				delegateReplyEvent.Name = startOpName + Deployment.c_Reply + Deployment.cEventHandler;
				delegateReplyEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				delegateReplyEvent.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(object), "sender"));
				delegateReplyEvent.Parameters.Add(
					new CodeParameterDeclarationExpression(ctdEAReply.Name, "e"));
				// add delegate to namespace
				nsLocalSvc.Types.Add(delegateReplyEvent);
				#endregion

				#region add reply method to interface
				// void Start_Reply(OutputType output);
				CodeMemberMethod methodReply = new CodeMemberMethod();
				methodReply.Name = startOpName + Deployment.c_Reply;
				methodReply.Attributes = MemberAttributes.Public;
				methodReply.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(Guid), "workflowInstanceId"));
				methodReply.Parameters.Add(
					new CodeParameterDeclarationExpression(typeRefOutput, "output"));
				// add output method to interface
				_ctdLocalInterface.Members.Add(methodReply);
				#endregion
			}

			#region add start event to interface
			// event XEventHandler
			CodeMemberEvent eventStart = new CodeMemberEvent();
			eventStart.Name = startOpName;
			eventStart.Type = new CodeTypeReference(delegateEvent.Name);
			eventStart.Attributes = (MemberAttributes)0;
			// add event to local interface
			_ctdLocalInterface.Members.Add(eventStart);
			#endregion

		}

		private void generateLocalSvcClass(CodeNamespace nsLocalSvc,
			CodeTypeReference typeRefInput, CodeTypeReference typeRefOutput, string startOpName)
		{
			#region add constructor
			CodeConstructor ctorLocalSvc = new CodeConstructor();
			ctorLocalSvc.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			ctorLocalSvc.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(WorkflowRuntime), "workflowRuntime"));
			// add to local service class
			_ctdLocalService.Members.Add(ctorLocalSvc);
			#endregion

			#region add events
			// create start event
			CodeMemberEvent eventStart = new CodeMemberEvent();
			eventStart.Name = startOpName;
			eventStart.Attributes = MemberAttributes.Final | MemberAttributes.Public;
			eventStart.Type = new CodeTypeReference(startOpName + Deployment.cEventHandler);
			// add event to local service class
			_ctdLocalService.Members.Add(eventStart);

			if ( typeRefOutput != null ) {
				// create reply event
				CodeMemberEvent eventReply = new CodeMemberEvent();
				eventReply.Name = startOpName + Deployment.c_Reply + "Event";
				eventReply.Attributes = MemberAttributes.Final | MemberAttributes.Public;
				eventReply.Type = new CodeTypeReference(startOpName + Deployment.c_Reply + Deployment.cEventHandler);
				// add event to local service class
				_ctdLocalService.Members.Add(eventReply);
			}
			#endregion

			#region implement raise start event method
			CodeMemberMethod methodRaiseStart = new CodeMemberMethod();
			methodRaiseStart.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			methodRaiseStart.Name = Deployment.cRaise + startOpName + Deployment.cEvent;
			methodRaiseStart.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(Guid), "workflowInstanceId"));
			if ( typeRefInput != null ) {
				methodRaiseStart.Parameters.Add(
					new CodeParameterDeclarationExpression(typeRefInput, "input"));
			}
			// XEventArgs e = new XEventArgs(workflowInstanceId[, input]);
			CodeObjectCreateExpression createE = new CodeObjectCreateExpression();
			createE.CreateType = new CodeTypeReference(startOpName + Deployment.cEventArgs);
			createE.Parameters.Add(new CodeArgumentReferenceExpression("workflowInstanceId"));
			if ( typeRefInput != null ) {
				createE.Parameters.Add(new CodeArgumentReferenceExpression("input"));
			}
			methodRaiseStart.Statements.Add(
				new CodeVariableDeclarationStatement(
					startOpName + Deployment.cEventArgs,
					"e",
					createE));
			// XEventHandler tmp = this.StartOp;
			methodRaiseStart.Statements.Add(
				new CodeVariableDeclarationStatement(
					startOpName + Deployment.cEventHandler,
					"tmp",
					new CodeEventReferenceExpression(new CodeThisReferenceExpression(), startOpName)));
			// if ( tmp != null )
			methodRaiseStart.Statements.Add(
				new CodeConditionStatement(
					new CodeBinaryOperatorExpression(
						new CodeVariableReferenceExpression("tmp"),
						CodeBinaryOperatorType.IdentityInequality,
						new CodePrimitiveExpression(null)),
					new CodeStatement[] {
						new CodeExpressionStatement(
						new CodeDelegateInvokeExpression( // tmp(this, e);
							new CodeVariableReferenceExpression("tmp"),
							new CodePrimitiveExpression(null),
							new CodeVariableReferenceExpression("e")))
					}));
			_ctdLocalService.Members.Add(methodRaiseStart);
			#endregion

			if ( typeRefOutput != null ) {
				#region implement output method
				// public void Start_Reply(Guid workflowInstanceId, OutputType output) {
				CodeMemberMethod methReply = new CodeMemberMethod();
				methReply.Name = startOpName + Deployment.c_Reply;
				methReply.Attributes = MemberAttributes.Final | MemberAttributes.Public;
				methReply.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(Guid), "workflowInstanceId"));
				methReply.Parameters.Add(
					new CodeParameterDeclarationExpression(typeRefOutput, "output"));
				//		X_ReplyEventArgs e = new X_ReplyEventArgs(workflowInstanceId, output);
				methReply.Statements.Add(
					new CodeVariableDeclarationStatement(
						startOpName + Deployment.c_Reply + Deployment.cEventArgs,
						"e",
						new CodeObjectCreateExpression(
							startOpName + Deployment.c_Reply + Deployment.cEventArgs,
							new CodeVariableReferenceExpression("workflowInstanceId"),
							new CodeVariableReferenceExpression("output"))));
				//		XReplyEventHandler tmp = this.XReplyEvent;
				methReply.Statements.Add(
					new CodeVariableDeclarationStatement(
						startOpName + Deployment.c_Reply + Deployment.cEventHandler,
						"tmp",
						new CodeEventReferenceExpression(
							new CodeThisReferenceExpression(),
							startOpName + Deployment.c_Reply + Deployment.cEvent)));
				//		if ( tmp != null )
				methReply.Statements.Add(
					new CodeConditionStatement(
						new CodeBinaryOperatorExpression(
							new CodeVariableReferenceExpression("tmp"),
							CodeBinaryOperatorType.IdentityInequality,
							new CodePrimitiveExpression(null)),
					//			tmp(this, e);
					new CodeExpressionStatement(
					new CodeDelegateInvokeExpression(
						new CodeVariableReferenceExpression("tmp"),
						new CodePrimitiveExpression(null),
						new CodeVariableReferenceExpression("e")))));
				// }
				_ctdLocalService.Members.Add(methReply);
				#endregion
			}
		}

		#endregion

		#region Generate External Data Exchange Code

		private void generateProxyForMashup(Deployment deployment)
		{
			#region Initialize
			TypeProvider typeProvider = GetService(typeof(ITypeProvider)) as TypeProvider;
			Debug.Assert(typeProvider != null);

			CodeNamespace nsEmpty = new CodeNamespace();
			nsEmpty.Imports.Add(new CodeNamespaceImport("System.Workflow.Activities"));
			_codeLocalService.Namespaces.Add(nsEmpty);
			#endregion

			#region Generate Proxy Class

			#region create constructor
			CodeConstructor ctorProxy = new CodeConstructor();
			ctorProxy.Attributes = MemberAttributes.Public;
			ctorProxy.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Initialization"));
			ctorProxy.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Initialization"));
			// ExternalDataExchangeService extdatasvc = new ExternalDataExchangeService()
			ctorProxy.Statements.Add(
				new CodeVariableDeclarationStatement(
					typeof(ExternalDataExchangeService),
					Deployment.cExtDataSvc,
					new CodeObjectCreateExpression(typeof(ExternalDataExchangeService))));
			// _wfRuntime = new WorkflowRuntime();
			ctorProxy.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					new CodeObjectCreateExpression(typeof(WorkflowRuntime))));
			// _wfRuntime.AddService(extdatasvc);
			ctorProxy.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cAddService,
					new CodeVariableReferenceExpression(Deployment.cExtDataSvc)));
			// _wfRuntime.StartRuntime();
			ctorProxy.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cStartRuntime));
			// extdatasvc.AddService(this);
			ctorProxy.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression(Deployment.cExtDataSvc),
					Deployment.cAddService,
					new CodeThisReferenceExpression()));
			// _wfInstance = null;
			ctorProxy.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfInstance),
					new CodePrimitiveExpression(null)));
			_ctdLocalService.Members.Add(ctorProxy);
			#endregion

			#region add private fields
			_ctdLocalService.Members.Add(
				new CodeMemberField(typeof(WorkflowRuntime), Deployment.c_wfRuntime));
			_ctdLocalService.Members.Add(
				new CodeMemberField(typeof(WorkflowInstance), Deployment.c_wfInstance));
			#endregion

			#region add properties
			CodeMemberProperty propWFRTM = new CodeMemberProperty();
			propWFRTM.Name = Deployment.cRuntime;
			propWFRTM.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			propWFRTM.Type = new CodeTypeReference(typeof(WorkflowRuntime));
			propWFRTM.HasGet = true;
			propWFRTM.HasSet = false;
			propWFRTM.GetStatements.Add(
				new CodeMethodReturnStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime)));
			_ctdLocalService.Members.Add(propWFRTM);
			#endregion

			#region add IDisposable
			// add IDisposable to class
			_ctdLocalService.BaseTypes.Add(typeof(IDisposable));

			// implement Dispose method
			CodeMemberMethod methDispose = new CodeMemberMethod();
			methDispose.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			methDispose.Name = Deployment.cDispose;
			methDispose.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "IDisposable Members"));
			methDispose.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "IDisposable Members"));
			methDispose.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cStopRuntime));
			methDispose.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cDispose));
			methDispose.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					new CodePrimitiveExpression(null)));
			methDispose.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfInstance),
					new CodePrimitiveExpression(null)));
			_ctdLocalService.Members.Add(methDispose);
			#endregion

			#endregion

			#region Add Events
			foreach ( Repository.WorkflowEvent we in this.Workflow.Interface.Events ) {
				// create ExternalDataEventArgs class for event business object
				CodeTypeReference typeRefBObj;
				string classEventArgsName = createExternalDataEventArgsClass(
					deployment, typeProvider, we, out typeRefBObj);
				string delegateName = we.Name + Deployment.cEventHandler;

				// create delegate for ExternalDataEventArgs
				createEventDelegate(delegateName, classEventArgsName);

				// add event to interface (public interface I<WFNAME>Local)
				// event XEventHandler NAME;
				CodeMemberEvent interfaceEvent = new CodeMemberEvent();
				interfaceEvent.Name = we.Name;
				interfaceEvent.Type = new CodeTypeReference(delegateName);
				interfaceEvent.Attributes = (MemberAttributes)0;
				// add event to local interface
				_ctdLocalInterface.Members.Add(interfaceEvent);

				// add event to interface implementation (public class <WFNAME>Local : I<WFNAME>Local)
				CodeMemberEvent classEvent = new CodeMemberEvent();
				classEvent.Name = we.Name;
				classEvent.Attributes = MemberAttributes.Final | MemberAttributes.Public;
				classEvent.Type = new CodeTypeReference(delegateName);
				// add event to local service class
				_ctdLocalService.Members.Add(classEvent);

				// add "RaiseEvent" method to interface implementation
				addRaiseEventToInterfaceImplementation(we, typeRefBObj, classEventArgsName, delegateName);

				// add properties to code beside

				// create workflowInstanceId Property
				_memberCreation.CreateProperty(this.FullClassName,
											   PropertyNames.WorkflowInstanceId,
											   typeof(Guid),
											   null,
											   true,
											   false,
											   false,
											   null,
											   false);

				//// add EventArgs property and assign to input property
				//if ( typeRefBObj != null ) {
				//    Type t = typeProvider.GetType(this.Namespace + "." + classEventArgsName);
				//    _memberCreation.CreatePropertyForWCFInputEventArgs(this.FullClassName,
				//        classEventArgsName,
				//        t,
				//        we.BusinessObjectName, PropertyNames.WorkflowInstanceId);
				//}
				// add event method to wcf service contract
				CodeMemberMethod meth = new CodeMemberMethod();
				meth.Attributes = 0;
				meth.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(OperationContractAttribute)),
						new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true))));
				meth.Name = we.Name;
				if ( typeRefBObj != null ) {
					meth.Parameters.Add(
						new CodeParameterDeclarationExpression(typeRefBObj, "input"));
				}
				_ctdInterface.Members.Add(meth);
			}
			#endregion

			#region Add Methods
			foreach ( Repository.WorkflowMethod wm in this.Workflow.Interface.Methods ) {
				CodeTypeReference typeRefInput, typeRefOutput;
				// create EventArgs class for interface method implementation
				string classEventArgsName = createEventArgsClass(deployment, typeProvider, wm,
					out typeRefInput, out typeRefOutput);
				string delegateName = wm.Name + Deployment.cEventHandler;

				// create delegate for EventArgs
				if ( string.IsNullOrEmpty(classEventArgsName) ) {
					classEventArgsName = wm.Name + Deployment.cEventArgs;
				} else {
					createEventDelegate(delegateName, classEventArgsName);
				}

				// add method to interface
				CodeMemberMethod interfaceMethod = new CodeMemberMethod();
				interfaceMethod.Name = wm.Name;
				interfaceMethod.Attributes = MemberAttributes.Public;
				interfaceMethod.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(Guid), "workflowInstanceId"));
				if ( typeRefInput != null ) {
					// add method input parameter
					interfaceMethod.Parameters.Add(
						new CodeParameterDeclarationExpression(typeRefInput, Deployment.cMethodInput));
				}
				if ( typeRefOutput != null ) {
					// set return value
					interfaceMethod.ReturnType = typeRefOutput;
				}
				// add output method to interface
				_ctdLocalInterface.Members.Add(interfaceMethod);

				// add event to interface implementation class
				CodeMemberEvent classEvent = new CodeMemberEvent();
				classEvent.Name = wm.Name + Deployment.cEvent;
				classEvent.Attributes = MemberAttributes.Final | MemberAttributes.Public;
				classEvent.Type = new CodeTypeReference(delegateName);
				// add event to local service class
				_ctdLocalService.Members.Add(classEvent);

				// add method implementation to invoke the created event
				addMethodToInterfaceImplementation(wm, typeRefInput, typeRefOutput,
												   classEventArgsName, delegateName);

				// add method to wcf service callback contract
				CodeMemberMethod meth = new CodeMemberMethod();
				meth.Attributes = 0;
				if ( typeRefOutput != null ) {
					meth.CustomAttributes.Add(
						new CodeAttributeDeclaration(
							new CodeTypeReference(typeof(OperationContractAttribute))));
					meth.ReturnType = typeRefOutput;
				} else {
					meth.CustomAttributes.Add(
						new CodeAttributeDeclaration(
							new CodeTypeReference(typeof(OperationContractAttribute)),
							new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true))));
				}
				meth.Name = wm.Name;
				if ( typeRefInput != null ) {
					meth.Parameters.Add(
						new CodeParameterDeclarationExpression(typeRefInput, Deployment.cMethodOutput));
				}
				_ctdInterfaceCallback.Members.Add(meth);
			}
			#endregion
		}
		private void generateProxyForWCFService(Deployment deployment)
		{
			#region Initialize
			TypeProvider typeProvider = GetService(typeof(ITypeProvider)) as TypeProvider;
			Debug.Assert(typeProvider != null);

			CodeNamespace nsEmpty = new CodeNamespace();
			nsEmpty.Imports.Add(new CodeNamespaceImport("System"));
			nsEmpty.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
			nsEmpty.Imports.Add(new CodeNamespaceImport("System.Text"));
			nsEmpty.Imports.Add(new CodeNamespaceImport("System.Workflow.Activities"));
			nsEmpty.Imports.Add(new CodeNamespaceImport("System.Workflow.Runtime"));
			nsEmpty.Imports.Add(new CodeNamespaceImport(this.Namespace));
			nsEmpty.Imports.Add(new CodeNamespaceImport(this.NamespaceData));
			_codeLocalService.Namespaces.Add(nsEmpty);

			#region create Host Service Constructor
			CodeConstructor ctorHost = new CodeConstructor();
			ctorHost.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), "_callback"),
					new CodePrimitiveExpression(null)));
			ctorHost.Statements.Add(
				new CodeAttachEventStatement(
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name),
							"Instance"),
						"Runtime"),
					"WorkflowCompleted",
					new CodeObjectCreateExpression(
						new CodeTypeReference(
							"EventHandler",
							new CodeTypeReference(typeof(WorkflowCompletedEventArgs))),
						new CodeMethodReferenceExpression(
							new CodeThisReferenceExpression(), "runtime_WorkflowCompleted"))));
			ctorHost.Statements.Add(
				new CodeAttachEventStatement(
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name),
							"Instance"),
						"Runtime"),
					"WorkflowAborted",
					new CodeObjectCreateExpression(
						new CodeTypeReference(
							"EventHandler",
							new CodeTypeReference(typeof(WorkflowEventArgs))),
						new CodeMethodReferenceExpression(
							new CodeThisReferenceExpression(), "runtime_WorkflowAborted"))));
			ctorHost.Statements.Add(
				new CodeAttachEventStatement(
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name),
							"Instance"),
						"Runtime"),
					"WorkflowTerminated",
					new CodeObjectCreateExpression(
						new CodeTypeReference(
							"EventHandler",
							new CodeTypeReference(typeof(WorkflowTerminatedEventArgs))),
						new CodeMethodReferenceExpression(
							new CodeThisReferenceExpression(), "runtime_WorkflowTerminated"))));
			_ctdHostService.Members.Add(ctorHost);
			#endregion

			#region create Host Service proxy workflow runtime event handlers
			CodeMemberMethod mCleanUp = new CodeMemberMethod();
			mCleanUp.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			mCleanUp.Name = "cleanup";
			mCleanUp.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(Guid), "instanceId"));
			CodeConditionStatement condCleanUp = new CodeConditionStatement();
			mCleanUp.Statements.Add(condCleanUp);
			condCleanUp.Condition =
				new CodeBinaryOperatorExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), "_instanceId"),
					CodeBinaryOperatorType.ValueEquality,
					new CodeArgumentReferenceExpression("instanceId"));
			#region Remove Workflow Events
			condCleanUp.TrueStatements.Add(
				new CodeRemoveEventStatement(
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name),
							"Instance"),
						"Runtime"),
					"WorkflowCompleted",
					new CodeObjectCreateExpression(
						new CodeTypeReference(
							"EventHandler",
							new CodeTypeReference(typeof(WorkflowCompletedEventArgs))),
						new CodeMethodReferenceExpression(
							new CodeThisReferenceExpression(), "runtime_WorkflowCompleted"))));
			condCleanUp.TrueStatements.Add(
				new CodeRemoveEventStatement(
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name),
							"Instance"),
						"Runtime"),
					"WorkflowAborted",
					new CodeObjectCreateExpression(
						new CodeTypeReference(
							"EventHandler",
							new CodeTypeReference(typeof(WorkflowEventArgs))),
						new CodeMethodReferenceExpression(
							new CodeThisReferenceExpression(), "runtime_WorkflowAborted"))));
			condCleanUp.TrueStatements.Add(
				new CodeRemoveEventStatement(
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name),
							"Instance"),
						"Runtime"),
					"WorkflowTerminated",
					new CodeObjectCreateExpression(
						new CodeTypeReference(
							"EventHandler",
							new CodeTypeReference(typeof(WorkflowTerminatedEventArgs))),
						new CodeMethodReferenceExpression(
							new CodeThisReferenceExpression(), "runtime_WorkflowTerminated"))));
			#endregion
			condCleanUp.TrueStatements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), "_callback"),
					new CodePrimitiveExpression(null)));
			_ctdHostService.Members.Add(mCleanUp);
			CodeMemberMethod mCompleted = new CodeMemberMethod();
			mCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			mCompleted.Name = "runtime_WorkflowCompleted";
			mCompleted.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(object), "sender"));
			mCompleted.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(WorkflowCompletedEventArgs), "e"));
			// cleanup(e.WorkflowInstance.InstanceId);
			mCompleted.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeThisReferenceExpression(),
					mCleanUp.Name,
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeArgumentReferenceExpression("e"), "WorkflowInstance"),
						"InstanceId")));
			_ctdHostService.Members.Add(mCompleted);
			CodeMemberMethod mAborted = new CodeMemberMethod();
			mAborted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			mAborted.Name = "runtime_WorkflowAborted";
			mAborted.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(object), "sender"));
			mAborted.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(WorkflowEventArgs), "e"));
			// cleanup(e.WorkflowInstance.InstanceId);
			mAborted.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeThisReferenceExpression(),
					mCleanUp.Name,
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeArgumentReferenceExpression("e"), "WorkflowInstance"),
						"InstanceId")));
			_ctdHostService.Members.Add(mAborted);
			CodeMemberMethod mTerminated = new CodeMemberMethod();
			mTerminated.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			mTerminated.Name = "runtime_WorkflowTerminated";
			mTerminated.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(object), "sender"));
			mTerminated.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(WorkflowTerminatedEventArgs), "e"));
			// cleanup(e.WorkflowInstance.InstanceId);
			mTerminated.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeThisReferenceExpression(),
					mCleanUp.Name,
					new CodePropertyReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeArgumentReferenceExpression("e"), "WorkflowInstance"),
						"InstanceId")));
			_ctdHostService.Members.Add(mTerminated);
			#endregion

			#region create Host Service private field
			_ctdHostService.Members.Add(
				new CodeMemberField(typeof(Guid), "_instanceId"));
			_ctdHostService.Members.Add(
				new CodeMemberField(_ctdInterfaceCallback.Name, "_callback"));
			#endregion

			#endregion

			#region Generate Proxy Class

			#region add static members
			// private static PROXY _instance = new PROXY();
			CodeMemberField fieldInstance = new CodeMemberField();
			fieldInstance.Attributes = MemberAttributes.Private | MemberAttributes.Static;
			fieldInstance.InitExpression = new CodeObjectCreateExpression(_ctdLocalService.Name);
			fieldInstance.Name = "_instance";
			fieldInstance.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Static Members"));
			fieldInstance.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Static Members"));
			fieldInstance.Type = new CodeTypeReference(_ctdLocalService.Name);
			_ctdLocalService.Members.Add(fieldInstance);
			// public static PROXY Instance { get {...} }
			CodeMemberProperty propInstance = new CodeMemberProperty();
			propInstance.Attributes = MemberAttributes.Public | MemberAttributes.Static;
			propInstance.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Static Members"));
			propInstance.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Static Members"));
			propInstance.GetStatements.Add(
				new CodeMethodReturnStatement(
					new CodeFieldReferenceExpression(
						new CodeTypeReferenceExpression(_ctdLocalService.Name), "_instance")));
			propInstance.HasGet = true;
			propInstance.HasSet = false;
			propInstance.Name = "Instance";
			propInstance.Type = new CodeTypeReference(_ctdLocalService.Name);
			_ctdLocalService.Members.Add(propInstance);
			#endregion

			#region create constructor
			CodeConstructor ctorProxy = new CodeConstructor();
			ctorProxy.Attributes = MemberAttributes.Private;
			ctorProxy.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Initialization"));
			ctorProxy.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "Initialization"));
			// ExternalDataExchangeService extdatasvc = new ExternalDataExchangeService()
			ctorProxy.Statements.Add(
				new CodeVariableDeclarationStatement(
					typeof(ExternalDataExchangeService),
					Deployment.cExtDataSvc,
					new CodeObjectCreateExpression(typeof(ExternalDataExchangeService))));
			// _wfRuntime = new WorkflowRuntime();
			ctorProxy.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					new CodeObjectCreateExpression(typeof(WorkflowRuntime))));
			// _wfRuntime.AddService(extdatasvc);
			ctorProxy.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cAddService,
					new CodeVariableReferenceExpression(Deployment.cExtDataSvc)));
			// _wfRuntime.AddService(new AsyncService());
			ctorProxy.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cAddService,
					new CodeObjectCreateExpression(typeof(AsyncService))));
			if ( Workflow.ExtendedProperties.UseDefaultPersistence ) {
				ctorProxy.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
						Deployment.cAddService,
						new CodeObjectCreateExpression(
							typeof(SqlWorkflowPersistenceService),
							new CodeArrayIndexerExpression(
								new CodePropertyReferenceExpression(
									new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
									"AppSettings"),
								new CodePrimitiveExpression("PersistenceConnection")))));
				//new CodePrimitiveExpression(Workflow.ExtendedProperties.DefaultPersistenceConnection))));
			}
			if ( Workflow.ExtendedProperties.UseDefaultTracking ) {
				ctorProxy.Statements.Add(
					new CodeVariableDeclarationStatement(
						typeof(SqlTrackingService),
						"trackingService",
						new CodeObjectCreateExpression(
							typeof(SqlTrackingService),
							new CodeArrayIndexerExpression(
								new CodePropertyReferenceExpression(
									new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
									"AppSettings"),
								new CodePrimitiveExpression("TrackingConnection")))));
				//new CodePrimitiveExpression(Workflow.ExtendedProperties.DefaultTrackingConnection))));
				ctorProxy.Statements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("trackingService"),
							"IsTransactional"),
						new CodePrimitiveExpression(Workflow.ExtendedProperties.IsTransactional)));
				ctorProxy.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
						Deployment.cAddService,
						new CodeVariableReferenceExpression("trackingService")));
			}
			// _wfRuntime.StartRuntime();
			ctorProxy.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cStartRuntime));
			// extdatasvc.AddService(this);
			ctorProxy.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression(Deployment.cExtDataSvc),
					Deployment.cAddService,
					new CodeThisReferenceExpression()));
			_ctdLocalService.Members.Add(ctorProxy);
			#endregion

			#region add private fields
			_ctdLocalService.Members.Add(
				new CodeMemberField(typeof(WorkflowRuntime), Deployment.c_wfRuntime));
			#endregion

			#region add properties
			CodeMemberProperty propWFRTM = new CodeMemberProperty();
			propWFRTM.Name = Deployment.cRuntime;
			propWFRTM.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			propWFRTM.Type = new CodeTypeReference(typeof(WorkflowRuntime));
			propWFRTM.HasGet = true;
			propWFRTM.HasSet = false;
			propWFRTM.GetStatements.Add(
				new CodeMethodReturnStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime)));
			_ctdLocalService.Members.Add(propWFRTM);
			#endregion

			#region add and implement IDisposable
			// add IDisposable to class
			_ctdLocalService.BaseTypes.Add(typeof(IDisposable));

			// implement Dispose method
			CodeMemberMethod methDispose = new CodeMemberMethod();
			methDispose.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			methDispose.Name = Deployment.cDispose;
			methDispose.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "IDisposable Members"));
			methDispose.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "IDisposable Members"));
			methDispose.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cStopRuntime));
			methDispose.Statements.Add(
				new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					Deployment.cDispose));
			methDispose.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
					new CodePrimitiveExpression(null)));
			_ctdLocalService.Members.Add(methDispose);
			#endregion

			#endregion

			//Not necessary anymore?
			#region Add Events
			foreach ( Repository.WorkflowEvent we in this.Workflow.Interface.Events ) {
				// create ExternalDataEventArgs class for event business object
				CodeTypeReference typeRefBObj;
				string classEventArgsName = createExternalDataEventArgsClass(deployment, typeProvider, we, out typeRefBObj);
				string delegateName = we.Name + Deployment.cEventHandler;

				// create delegate for ExternalDataEventArgs
				createEventDelegate(delegateName, classEventArgsName);

				// add event to interface (public interface I<WFNAME>Local)
				// event XEventHandler NAME;
				CodeMemberEvent interfaceEvent = new CodeMemberEvent();
				interfaceEvent.Name = we.Name;
				interfaceEvent.Type = new CodeTypeReference(delegateName);
				interfaceEvent.Attributes = (MemberAttributes)0;
				// add event to local interface
				_ctdLocalInterface.Members.Add(interfaceEvent);

				// add event to interface implementation (public class <WFNAME>Local : I<WFNAME>Local)
				CodeMemberEvent classEvent = new CodeMemberEvent();
				classEvent.Name = we.Name;
				classEvent.Attributes = MemberAttributes.Final | MemberAttributes.Public;
				classEvent.Type = new CodeTypeReference(delegateName);
				// add event to local service class
				_ctdLocalService.Members.Add(classEvent);

				// add "RaiseEvent" method to interface implementation
				addRaiseEventToInterfaceImplementationForWCF(we, typeRefBObj, classEventArgsName, delegateName);

				// add properties to code beside

				// create workflowInstanceId Property
				_memberCreation.CreateProperty(this.FullClassName,
											   PropertyNames.WorkflowInstanceId,
											   typeof(Guid),
											   null,
											   true,
											   false,
											   false,
											   null,
											   false);

				//// add EventArgs property and assign to input property
				//if ( typeRefBObj != null ) {
				//    Type t = typeProvider.GetType(this.Namespace + "." + classEventArgsName);
				//    _memberCreation.CreatePropertyForWCFInputEventArgs(this.FullClassName,
				//        classEventArgsName,
				//        t,
				//        we.BusinessObjectName, PropertyNames.WorkflowInstanceId);
				//}
				#region add event method to wcf service contract
				CodeMemberMethod meth = new CodeMemberMethod();
				meth.Attributes = 0;
				meth.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(OperationContractAttribute)),
						new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true))));
				meth.Name = we.Name;
				if ( typeRefBObj != null ) {
					meth.Parameters.Add(
						new CodeParameterDeclarationExpression(typeRefBObj, "input"));
				}
				_ctdInterface.Members.Add(meth);
				#endregion

				#region add event method implementation to host service
				CodeMemberMethod methImpl = new CodeMemberMethod();
				methImpl.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				methImpl.Name = we.Name;
				if ( typeRefBObj != null ) {
					methImpl.Parameters.Add(
						new CodeParameterDeclarationExpression(typeRefBObj, "input"));
				}
				methImpl.Statements.Add(
					new CodeConditionStatement(
						new CodeBinaryOperatorExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), "_callback"),
							CodeBinaryOperatorType.IdentityEquality,
							new CodePrimitiveExpression(null)),
						new CodeAssignStatement(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), "_callback"),
							new CodeMethodInvokeExpression(
								new CodeMethodReferenceExpression(
									new CodePropertyReferenceExpression(
										new CodeTypeReferenceExpression(typeof(OperationContext)),
										"Current"),
									"GetCallbackChannel",
									new CodeTypeReference(_ctdInterfaceCallback.Name))))));
				CodeMethodInvokeExpression invokeRaise = new CodeMethodInvokeExpression();
				invokeRaise.Method = new CodeMethodReferenceExpression(
					new CodePropertyReferenceExpression(
						new CodeTypeReferenceExpression(_ctdLocalService.Name),
						"Instance"),
					"Raise" + we.Name);
				if ( typeRefBObj != null ) {
					invokeRaise.Parameters.Add(new CodeArgumentReferenceExpression("input"));
				}
				if ( we.IsStart ) {
					methImpl.Statements.Add(
						new CodeAssignStatement(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), "_instanceId"),
							invokeRaise));
				} else {
					invokeRaise.Parameters.Add(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), "_instanceId"));
					methImpl.Statements.Add(invokeRaise);
				}
				_ctdHostService.Members.Add(methImpl);
				#endregion
			}
			#endregion

			#region Add Methods
			foreach ( Repository.WorkflowMethod wm in this.Workflow.Interface.Methods ) {
				CodeTypeReference typeRefInput, typeRefOutput;
				// create EventArgs class for interface method implementation
				string classEventArgsName = createEventArgsClass(deployment, typeProvider, wm,
					out typeRefInput, out typeRefOutput);
				string delegateName = wm.Name + Deployment.cEventHandler;

				// create delegate for EventArgs
				if ( string.IsNullOrEmpty(classEventArgsName) ) {
					classEventArgsName = wm.Name + Deployment.cEventArgs;
				} else {
					createEventDelegate(delegateName, classEventArgsName);
				}

				// add method to interface
				CodeMemberMethod interfaceMethod = new CodeMemberMethod();
				interfaceMethod.Name = wm.Name;
				interfaceMethod.Attributes = MemberAttributes.Public;
				interfaceMethod.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(Guid), "workflowInstanceId"));
				if ( typeRefInput != null ) {
					// add process output parameter
					interfaceMethod.Parameters.Add(
						new CodeParameterDeclarationExpression(typeRefInput, Deployment.cMethodInput));
				}
				if ( typeRefOutput != null ) {
					// set return value
					interfaceMethod.ReturnType = typeRefOutput;
				}
				// add output method to interface
				_ctdLocalInterface.Members.Add(interfaceMethod);

				// add event to interface implementation class
				CodeMemberEvent classEvent = new CodeMemberEvent();
				classEvent.Name = wm.Name + Deployment.cEvent;
				classEvent.Attributes = MemberAttributes.Final | MemberAttributes.Public;
				classEvent.Type = new CodeTypeReference(delegateName);
				// add event to local service class
				_ctdLocalService.Members.Add(classEvent);

				// add method implementation to invoke the created event
				addMethodToInterfaceImplementation(wm, typeRefInput, typeRefOutput,
												   classEventArgsName, delegateName);

				#region add method to wcf service callback contract
				CodeMemberMethod meth = new CodeMemberMethod();
				if ( typeRefOutput != null ) {
					meth.CustomAttributes.Add(
						new CodeAttributeDeclaration(
							new CodeTypeReference(typeof(OperationContractAttribute))));
					meth.ReturnType = typeRefOutput;
				} else {
					meth.CustomAttributes.Add(
						new CodeAttributeDeclaration(
							new CodeTypeReference(typeof(OperationContractAttribute)),
							new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true))));
				}
				meth.Name = wm.Name;
				if ( typeRefInput != null ) {
					meth.Parameters.Add(
						new CodeParameterDeclarationExpression(typeRefInput, Deployment.cMethodOutput));
				}
				_ctdInterfaceCallback.Members.Add(meth);
				#endregion

				#region add method implementation to host service
				// attach event
				ctorHost.Statements.Add(
					new CodeAttachEventStatement(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name), "Instance"),
						classEvent.Name,
						new CodeObjectCreateExpression(
							delegateName,
							new CodeMethodReferenceExpression(
								new CodeThisReferenceExpression(), "proxy_" + classEvent.Name))));
				// remove event handler on cleanup
				condCleanUp.TrueStatements.Add(
					new CodeRemoveEventStatement(
						new CodePropertyReferenceExpression(
							new CodeTypeReferenceExpression(_ctdLocalService.Name), "Instance"),
						classEvent.Name,
						new CodeObjectCreateExpression(
							delegateName,
							new CodeMethodReferenceExpression(
								new CodeThisReferenceExpression(), "proxy_" + classEvent.Name))));
				// create event handler method
				CodeMemberMethod methEventHandler = new CodeMemberMethod();
				methEventHandler.Attributes = MemberAttributes.Private | MemberAttributes.Final;
				methEventHandler.Name = "proxy_" + classEvent.Name;
				methEventHandler.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(object), "sender"));
				methEventHandler.Parameters.Add(
					new CodeParameterDeclarationExpression(classEventArgsName, "e"));

				CodeConditionStatement condIsInstance = new CodeConditionStatement();
				condIsInstance.Condition =
					new CodeBinaryOperatorExpression(
						new CodePropertyReferenceExpression(
							new CodeArgumentReferenceExpression("e"), "InstanceId"),
						CodeBinaryOperatorType.IdentityEquality,
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), "_instanceId"));
				CodeMethodInvokeExpression invokeWM = new CodeMethodInvokeExpression();
				invokeWM.Method = new CodeMethodReferenceExpression(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), "_callback"), wm.Name);
				if ( typeRefInput != null ) {
					invokeWM.Parameters.Add(
						new CodePropertyReferenceExpression(
							new CodeArgumentReferenceExpression("e"), Deployment.cPropMethodInput));
				}
				if ( typeRefOutput != null ) {
					condIsInstance.TrueStatements.Add(
						new CodeAssignStatement(
							new CodePropertyReferenceExpression(
								new CodeArgumentReferenceExpression("e"),
								Deployment.cPropMethodOutput),
							invokeWM));
				} else {
					condIsInstance.TrueStatements.Add(invokeWM);
				}
				methEventHandler.Statements.Add(condIsInstance);

				_ctdHostService.Members.Add(methEventHandler);
				#endregion
			}
			#endregion
		}

		/// <summary>
		/// Creates a delegate for the EventArgs class.<br/>
		/// ( public delegate void delegateName(object sender, eventArgsClassName e); )
		/// </summary>
		/// <param name="delegateName">The name of the delegate.</param>
		/// <param name="eventArgsClassName">The name of the type for the parameter 'e'.</param>
		private void createEventDelegate(string delegateName, string eventArgsClassName)
		{
			CodeTypeDelegate delegateEvent = new CodeTypeDelegate();
			delegateEvent.Name = delegateName;
			delegateEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			delegateEvent.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(object), "sender"));
			delegateEvent.Parameters.Add(
				new CodeParameterDeclarationExpression(eventArgsClassName, "e"));
			// add delegate to namespace
			_nsLocalService.Types.Add(delegateEvent);
		}
		/// <summary>
		/// Creates an ExternalDataEventArgs class for the Business Object of the WorkflowEvent we.
		/// </summary>
		/// <param name="typeProvider">A TypeProvider.</param>
		/// <param name="we">A Workflow Event.</param>
		/// <returns>The name of the generated class.</returns>
		private string createExternalDataEventArgsClass(
			Deployment deployment,
			TypeProvider typeProvider, WorkflowEvent we,
			out CodeTypeReference typeRefBObj)
		{
			typeRefBObj = null;
			if ( we.BusinessObjectID <= 0 ) {
				// no business object assigned
				return Deployment.cExternalDataEventArgs;
				// RETURN
			}
			string classEventArgsName = we.BusinessObjectName + Deployment.cExternalDataEventArgs;

			Type typeEEA = typeProvider.GetType(this.Namespace + "." + classEventArgsName);
			if ( typeEEA != null ) {
				typeRefBObj = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + we.BusinessObjectName));
				return classEventArgsName;
			}
			if ( typeRefBObj == null ) {
				// add WorkflowEvent Business Object
				deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData, typeProvider,
					we.BusinessObject, true);

				typeRefBObj = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + we.BusinessObjectName));
				// add property for business object to code beside
				if ( typeRefBObj != null ) {
					addPropertyForBObjectToCodeBeside(typeProvider, we.BusinessObject, typeRefBObj, string.Format("{0}_{1}", we.Name, we.BusinessObject.Name));
				}
			}
			CodeTypeDeclaration ctdExtEventArgs = new CodeTypeDeclaration(classEventArgsName);
			ctdExtEventArgs.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			//	add SerializableAttribute
			ctdExtEventArgs.CustomAttributes.Add(
				new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
			//	add Base Class
			ctdExtEventArgs.BaseTypes.Add(typeof(ExternalDataEventArgs));
			//	add Constuctor
			CodeConstructor ctorEventArgs = new CodeConstructor();
			ctorEventArgs.Attributes = MemberAttributes.Final | MemberAttributes.Public;
			ctorEventArgs.Parameters.Add(	// XExternalDataEventArgs(Guid instanceId, ...)
				new CodeParameterDeclarationExpression(typeof(Guid), "instanceId"));
			//			: base(instanceId);
			ctorEventArgs.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("instanceId"));

			if ( typeRefBObj != null ) {
				ctorEventArgs.Parameters.Add(	// XExternalDataEventArgs(..., InputType input)
					new CodeParameterDeclarationExpression(typeRefBObj, "input"));
				ctorEventArgs.Statements.Add(	// _input = input;
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_input"),
						new CodeArgumentReferenceExpression("input")));
			}
			ctdExtEventArgs.Members.Add(ctorEventArgs);
			if ( typeRefBObj != null ) {
				//	add private input data field
				ctdExtEventArgs.Members.Add(
					new CodeMemberField(typeRefBObj, "_input"));
				//	add public input data property (get)
				CodeMemberProperty propInput = new CodeMemberProperty();
				propInput.Name = "Input";
				propInput.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				propInput.Type = typeRefBObj;
				propInput.HasGet = true;
				propInput.HasSet = false;
				propInput.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_input")));

				ctdExtEventArgs.Members.Add(propInput);
			}
			// add EventArgs class to namespace
			_nsLocalService.Types.Add(ctdExtEventArgs);

			refreshTypeProvider(ref typeProvider, ref _codeLocalService);

			return classEventArgsName;
		}
		private string createEventArgsClass(
			Deployment deployment,
			TypeProvider typeProvider, WorkflowMethod wm,
			out CodeTypeReference typeRefInput, out CodeTypeReference typeRefOutput)
		{
			#region Initialization
			typeRefInput = null;
			typeRefOutput = null;
			string classEventArgsName = wm.Name + Deployment.cEventArgs;
			Type typeEEA = typeProvider.GetType(classEventArgsName);
			if ( typeEEA != null ) {
				if ( wm.InputBusinessObjectID > 0 ) {
					typeRefInput = new CodeTypeReference(
						typeProvider.GetType(this.NamespaceData + "." + wm.InputBusinessObjectName));
				}
				if ( wm.OutputBusinessObjectID > 0 ) {
					typeRefOutput = new CodeTypeReference(
						typeProvider.GetType(this.NamespaceData + "." + wm.OutputBusinessObjectName));
				}
				return null;
			}
			#endregion

			#region Add WorkflowEvent Input/Output Business Objects to Data code
			if ( wm.InputBusinessObjectID > 0 ) {
				deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData, typeProvider, wm.InputBusinessObject, this.GenerateDataContract);
				typeRefInput = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + wm.InputBusinessObjectName));
			}
			if ( wm.OutputBusinessObjectID > 0 ) {
				deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData, typeProvider, wm.OutputBusinessObject, this.GenerateDataContract);
				typeRefOutput = new CodeTypeReference(
					typeProvider.GetType(this.NamespaceData + "." + wm.OutputBusinessObjectName));
			}
			#endregion

			#region Add Properties for Input/Output Business Objects to Code Beside
			// add property for input business object to code beside
			if ( typeRefInput != null ) {
				addPropertyForBObjectToCodeBeside(typeProvider, wm.InputBusinessObject, typeRefInput, string.Format("{0}_{1}", wm.Name, wm.InputBusinessObject.Name));
			}

			// add property for output business object to code beside
			//if ( typeRefOutput != null ) {
			//    addPropertyForBObjectToCodeBeside(
			//        typeProvider, wm.OutputBusinessObject, typeRefOutput,
			//        wm.OutputBusinessObjectName);
			//}
			#endregion

			#region Initialize Method EventArgs Class
			CodeTypeDeclaration ctdEventArgs = new CodeTypeDeclaration(classEventArgsName);
			ctdEventArgs.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			//	add SerializableAttribute
			ctdEventArgs.CustomAttributes.Add(
				new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
			//	add Base Class
			ctdEventArgs.BaseTypes.Add(typeof(EventArgs));
			#endregion

			#region	Add Constuctor
			CodeConstructor ctorEventArgs = new CodeConstructor();
			ctorEventArgs.Attributes = MemberAttributes.Final | MemberAttributes.Public;
			ctorEventArgs.Parameters.Add(	// XEventArgs(Guid instanceId, ...)
				new CodeParameterDeclarationExpression(typeof(Guid), Deployment.cInstanceId));
			// this._instanceId = instanceId;
			ctorEventArgs.Statements.Add(
				new CodeAssignStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_InstanceId),
					new CodeArgumentReferenceExpression(Deployment.cInstanceId)));
			if ( typeRefInput != null ) {
				ctorEventArgs.Parameters.Add(	// XEventArgs(..., InputType methodInput)
					new CodeParameterDeclarationExpression(typeRefInput, Deployment.cMethodInput));
				ctorEventArgs.Statements.Add(	// _methodInput = methodInput;
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), Deployment.c_MethodInput),
						new CodeArgumentReferenceExpression(Deployment.cMethodInput)));
			}
			if ( typeRefOutput != null ) {
				ctorEventArgs.Statements.Add(	// _returnValue = null;
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), Deployment.c_MethodOutput),
						new CodePrimitiveExpression(null)));
			}
			ctdEventArgs.Members.Add(ctorEventArgs);
			#endregion

			#region Add Properties and Backing Fields

			#region Instance Id
			ctdEventArgs.Members.Add(
				new CodeMemberField(typeof(Guid), Deployment.c_InstanceId));
			CodeMemberProperty propInstId = new CodeMemberProperty();
			propInstId.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			propInstId.GetStatements.Add(
				new CodeMethodReturnStatement(
					new CodeFieldReferenceExpression(
						new CodeThisReferenceExpression(), Deployment.c_InstanceId)));
			propInstId.HasGet = true;
			propInstId.HasSet = false;
			propInstId.Name = Deployment.cPropInstanceId;
			propInstId.Type = new CodeTypeReference(typeof(Guid));
			ctdEventArgs.Members.Add(propInstId);
			#endregion
			#region Process Output
			if ( typeRefInput != null ) {
				//	add private output data field
				ctdEventArgs.Members.Add(
					new CodeMemberField(typeRefInput, Deployment.c_MethodInput));
				//	add public output data property (get)
				CodeMemberProperty propOutput = new CodeMemberProperty();
				propOutput.Name = Deployment.cPropMethodInput;
				propOutput.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				propOutput.Type = typeRefInput;
				propOutput.HasGet = true;
				propOutput.HasSet = false;
				propOutput.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), Deployment.c_MethodInput)));

				ctdEventArgs.Members.Add(propOutput);
			}
			#endregion
			#region Method Return Value
			if ( typeRefOutput != null ) {
				//	add private input data field
				ctdEventArgs.Members.Add(
					new CodeMemberField(typeRefOutput, Deployment.c_MethodOutput));
				//	add public input data property (get)
				CodeMemberProperty propInput = new CodeMemberProperty();
				propInput.Name = Deployment.cPropMethodOutput;
				propInput.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				propInput.Type = typeRefOutput;
				propInput.HasGet = true;
				propInput.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), Deployment.c_MethodOutput)));
				propInput.HasSet = true;
				propInput.SetStatements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), Deployment.c_MethodOutput),
						new CodePropertySetValueReferenceExpression()));

				ctdEventArgs.Members.Add(propInput);
			}
			#endregion

			#endregion

			// add EventArgs class to namespace
			_nsLocalService.Types.Add(ctdEventArgs);

			return classEventArgsName;
		}

		private void addRaiseEventToInterfaceImplementation(Repository.WorkflowEvent we,
			CodeTypeReference typeRefBObj, string classEventArgsName, string delegateName)
		{
			string summary = "";
			CodeMemberMethod methodRaiseEvent = new CodeMemberMethod();
			methodRaiseEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			methodRaiseEvent.Name = Deployment.cRaise + we.Name;
			if ( !string.IsNullOrEmpty(we.Description) ) {
				summary = we.Description;
			}
			if ( typeRefBObj != null ) {
				methodRaiseEvent.Parameters.Add(
					new CodeParameterDeclarationExpression(typeRefBObj, Deployment.cInput));
			}
			if ( we.IsStart ) {
				if ( string.IsNullOrEmpty(summary) ) {
					summary = "Use this method to start a new workflow instance.";
				} else {
					summary = string.Format("{0}{1} {2}",
						"Use this method to start a new workflow instance.", Environment.NewLine, summary);
				}
				methodRaiseEvent.Statements.Add(
					new CodeCommentStatement("create and start new workflow instance"));
				// _wfInstance = _wfRuntime.CreateWorkflow(typeof(<WFNAME>));
				methodRaiseEvent.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), Deployment.c_wfInstance),
						new CodeMethodInvokeExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
							Deployment.cCreateWorkflow,
							new CodeTypeOfExpression(this.FullClassName))));
				// _wfInstance.Start();
				methodRaiseEvent.Statements.Add(
					new CodeExpressionStatement(
						new CodeMethodInvokeExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), Deployment.c_wfInstance),
							Deployment.cStart)));
			} else {
				methodRaiseEvent.Statements.Add(
					new CodeConditionStatement(
					// if ( _wfInstance == null )
						new CodeBinaryOperatorExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), Deployment.c_wfInstance),
							CodeBinaryOperatorType.ValueEquality,
							new CodePrimitiveExpression(null)),
						new CodeStatement[] {
							// throw new NullReferenceException("First use a raise start event method to create a new workflow instance.");
							new CodeThrowExceptionStatement(
								new CodeObjectCreateExpression(
									typeof(NullReferenceException),
									new CodePrimitiveExpression("First use a raise start event method to create a new workflow instance.")))
						}));
			}
			if ( !string.IsNullOrEmpty(summary) ) {
				methodRaiseEvent.Comments.Add(new CodeCommentStatement(
					string.Format("<summary>{0} {1}{0} </summary>", Environment.NewLine, summary),
					true));
			}
			// XEventArgs e = new XEventArgs(workflowInstanceId[, input]);
			CodeObjectCreateExpression createE = new CodeObjectCreateExpression();
			createE.CreateType = new CodeTypeReference(classEventArgsName);
			createE.Parameters.Add(
				new CodePropertyReferenceExpression(
					new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), Deployment.c_wfInstance),
					"InstanceId"));
			if ( typeRefBObj != null ) {
				createE.Parameters.Add(new CodeArgumentReferenceExpression(Deployment.cInput));
			}
			methodRaiseEvent.Statements.Add(
				new CodeVariableDeclarationStatement(
					classEventArgsName,
					"e",
					createE));
			// XEventHandler tmp = this.StartOp;
			methodRaiseEvent.Statements.Add(
				new CodeVariableDeclarationStatement(
					delegateName,
					"tmp",
					new CodeEventReferenceExpression(new CodeThisReferenceExpression(), we.Name)));
			// if ( tmp != null )
			methodRaiseEvent.Statements.Add(
				new CodeConditionStatement(
					new CodeBinaryOperatorExpression(
						new CodeVariableReferenceExpression("tmp"),
						CodeBinaryOperatorType.IdentityInequality,
						new CodePrimitiveExpression(null)),
					new CodeStatement[] {
						new CodeExpressionStatement(
						new CodeDelegateInvokeExpression( // tmp(this, e);
							new CodeVariableReferenceExpression("tmp"),
							new CodePrimitiveExpression(null),
							new CodeVariableReferenceExpression("e")))
					}));
			_ctdLocalService.Members.Add(methodRaiseEvent);
		}
		private void addRaiseEventToInterfaceImplementationForWCF(Repository.WorkflowEvent we,
			CodeTypeReference typeRefBObj, string classEventArgsName, string delegateName)
		{
			string summary = "";
			CodeMemberMethod methodRaiseEvent = new CodeMemberMethod();
			methodRaiseEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			methodRaiseEvent.Name = Deployment.cRaise + we.Name;
			if ( !string.IsNullOrEmpty(we.Description) ) {
				summary = we.Description;
			}
			if ( typeRefBObj != null ) {
				methodRaiseEvent.Parameters.Add(
					new CodeParameterDeclarationExpression(typeRefBObj, Deployment.cInput));
			}
			if ( we.IsStart ) {
				if ( string.IsNullOrEmpty(summary) ) {
					summary = "Use this method to start a new workflow instance.";
				} else {
					summary = string.Format("{0}{1} {2}",
						"Use this method to start a new workflow instance.", Environment.NewLine, summary);
				}
				methodRaiseEvent.Statements.Add(
					new CodeCommentStatement("create and start new workflow instance"));
				methodRaiseEvent.Statements.Add(
					new CodeVariableDeclarationStatement(
						typeof(WorkflowInstance), "wfInstance",
						new CodeMethodInvokeExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), Deployment.c_wfRuntime),
							Deployment.cCreateWorkflow,
							new CodeTypeOfExpression(this.FullClassName))));
				methodRaiseEvent.Statements.Add(
					new CodeExpressionStatement(
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("wfInstance"),
							Deployment.cStart)));

				methodRaiseEvent.ReturnType = new CodeTypeReference(typeof(Guid));
			} else {
				methodRaiseEvent.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(Guid), "instanceId"));
			}
			if ( !string.IsNullOrEmpty(summary) ) {
				methodRaiseEvent.Comments.Add(new CodeCommentStatement(
					string.Format("<summary>{0} {1}{0} </summary>", Environment.NewLine, summary),
					true));
			}
			// XEventArgs e = new XEventArgs(workflowInstanceId[, input]);
			CodeObjectCreateExpression createE = new CodeObjectCreateExpression();
			createE.CreateType = new CodeTypeReference(classEventArgsName);
			if ( we.IsStart ) {
				createE.Parameters.Add(
					new CodePropertyReferenceExpression(
						new CodeVariableReferenceExpression("wfInstance"),
						"InstanceId"));
			} else {
				createE.Parameters.Add(new CodeArgumentReferenceExpression("instanceId"));
			}
			if ( typeRefBObj != null ) {
				createE.Parameters.Add(new CodeArgumentReferenceExpression(Deployment.cInput));
			}
			methodRaiseEvent.Statements.Add(
				new CodeVariableDeclarationStatement(
					classEventArgsName, "e", createE));
			// XEventHandler tmp = this.StartOp;
			methodRaiseEvent.Statements.Add(
				new CodeVariableDeclarationStatement(
					delegateName, "tmp",
					new CodeEventReferenceExpression(new CodeThisReferenceExpression(), we.Name)));
			// if ( tmp != null )
			methodRaiseEvent.Statements.Add(
				new CodeConditionStatement(
					new CodeBinaryOperatorExpression(
						new CodeVariableReferenceExpression("tmp"),
						CodeBinaryOperatorType.IdentityInequality,
						new CodePrimitiveExpression(null)),
					new CodeStatement[] {
						new CodeExpressionStatement(
						new CodeDelegateInvokeExpression( // tmp(this, e);
							new CodeVariableReferenceExpression("tmp"),
							new CodePrimitiveExpression(null),
							new CodeVariableReferenceExpression("e")))
					}));
			if ( we.IsStart ) {
				// return wfInstance.InstanceId;
				methodRaiseEvent.Statements.Add(
					new CodeMethodReturnStatement(
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("wfInstance"),
							"InstanceId")));
			}
			_ctdLocalService.Members.Add(methodRaiseEvent);
		}

		private void addMethodToInterfaceImplementation(Repository.WorkflowMethod wm,
			CodeTypeReference typeRefInput, CodeTypeReference typeRefOutput,
			string classEventArgsName, string delegateName)
		{
			CodeMemberMethod method = new CodeMemberMethod();
			method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			method.Name = wm.Name;
			method.Parameters.Add(
				new CodeParameterDeclarationExpression(typeof(Guid), Deployment.cWorkflowInstanceId));
			if ( typeRefInput != null ) {
				method.Parameters.Add(
					new CodeParameterDeclarationExpression(typeRefInput, Deployment.cMethodInput));
			}
			if ( typeRefOutput != null ) {
				method.ReturnType = typeRefOutput;
			}
			// XEventArgs e = new XEventArgs(workflowInstanceId[, input]);
			CodeObjectCreateExpression createE = new CodeObjectCreateExpression();
			createE.CreateType = new CodeTypeReference(classEventArgsName);
			createE.Parameters.Add(new CodeArgumentReferenceExpression(Deployment.cWorkflowInstanceId));
			if ( typeRefInput != null ) {
				createE.Parameters.Add(new CodeArgumentReferenceExpression(Deployment.cMethodInput));
			}
			method.Statements.Add(
				new CodeVariableDeclarationStatement(
					classEventArgsName,
					"e",
					createE));
			// initialize e.MethodOutput
			if ( typeRefOutput != null ) {
				method.Statements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("e"), Deployment.cPropMethodOutput),
						new CodeObjectCreateExpression(typeRefOutput)));
			}
			// XEventHandler tmp = this.MethodEvent;
			method.Statements.Add(
				new CodeVariableDeclarationStatement(
					delegateName,
					"tmp",
					new CodeEventReferenceExpression(new CodeThisReferenceExpression(), wm.Name + Deployment.cEvent)));
			// if ( tmp != null )
			method.Statements.Add(
				new CodeConditionStatement(
					new CodeBinaryOperatorExpression(
						new CodeVariableReferenceExpression("tmp"),
						CodeBinaryOperatorType.IdentityInequality,
						new CodePrimitiveExpression(null)),
					new CodeStatement[] {
						new CodeExpressionStatement(
						new CodeDelegateInvokeExpression( // tmp(this, e);
							new CodeVariableReferenceExpression("tmp"),
							new CodePrimitiveExpression(null),
							new CodeVariableReferenceExpression("e")))
					}));
			if ( typeRefOutput != null ) {
				method.Statements.Add(
					new CodeMethodReturnStatement(
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("e"), Deployment.cPropMethodOutput)));
			}
			_ctdLocalService.Members.Add(method);
		}

		#endregion

		#region Others

		private void writeStringToFile(string filepath, string content)
		{
			using ( FileStream fs = File.Create(filepath) ) { }
			File.SetAttributes(filepath, FileAttributes.Temporary);
			using ( StreamWriter sw = new StreamWriter(filepath, false) ) {
				sw.Write(content);
			}
		}

		private void refreshTypeProvider(ref TypeProvider typeProvider, ref CodeCompileUnit codeUnit)
		{
			typeProvider.RemoveCodeCompileUnit(codeUnit);
			typeProvider.AddCodeCompileUnit(codeUnit);
			typeProvider.GetTypes();
			Debug.Assert(( typeProvider.TypeLoadErrors.Count == 0 ));
		}
		private Repository.WebService getWebMethodService(Repository.WebMethod meth)
		{
			Repository.WebService ws = null;
			DataTable dt = Global.Data.GetRepositoryHierarchyParents(meth);
			if ( dt != null && dt.Rows.Count > 0 ) {
				foreach ( DataRow row in dt.Rows ) {
					if ( (int)row["parent_reptype_id"] == (int)Repository.ItemType.WebService ) {
						ws = new Repository.WebService((int)row["parent_id"]);
						break;
					}
				}
			}
			return ws;
		}

		private bool existsLogicalActivityMethod(string logactname)
		{
			bool exists = false;
			foreach ( CodeTypeMember member in _ctdLogActs.Members ) {
				CodeMemberMethod method = member as CodeMemberMethod;
				if ( method != null && method.Name == logactname ) {
					exists = true;
					break;
				}
			}
			return exists;
		}

		private void addProcessVariablesToCodeBeside(Deployment deployment)
		{
			TypeProvider typeProvider = (TypeProvider)this.GetService(typeof(ITypeProvider));
			MemberCreationService memberCreate = (MemberCreationService)this.GetService(typeof(IMemberCreationService));
			Debug.Assert(typeProvider != null);
			Debug.Assert(memberCreate != null);

			foreach ( Repository.WorkflowField var in _workflow.Interface.Fields ) {
				Type type = null;
				if ( var.BusinessObject != null ) {
					deployment.AddBusinessObjectToDataCode(this.DataCCU, this.NamespaceData,
						typeProvider, var.BusinessObject, this.GenerateDataContract);
					type = typeProvider.GetType(string.Format("{0}.{1}", this.NamespaceData, var.DataType));
				} else {
					type = Global.Data.GetDOTNETTypeofXSDDataType(var.DataType);
				}
				memberCreate.CreateProperty(_workflow.ExtendedProperties.FullName,
											var.Name,
											type,
											null, true, false, false, null, false);
			}
		}
		private void addMethodCodeSnippetsToCodeBeside(Deployment deployment)
		{
			foreach ( Repository.Workflow.MethodCodeSnippet snip in
						this.Workflow.ExtendedProperties.MethodCodeSnippets ) {
				CodeMemberMethod meth = deployment.getMethodFromCode(this.CodeBesideCCU, this.FullClassName, snip.MethodName);
				if ( meth == null ) {
					meth = new CodeMemberMethod();
					meth.Name = snip.MethodName;
					meth.ReturnType = new CodeTypeReference(snip.ReturnType);
					foreach ( Repository.Workflow.MethodParameter par in snip.MethodParameters ) {
						meth.Parameters.Add(
							new CodeParameterDeclarationExpression(par.Type, par.Name));
					}
					string code = snip.Code;
					if ( !string.IsNullOrEmpty(code) && !code.Contains(Environment.NewLine) ) {
						code = code.Replace("\n", Environment.NewLine);
					}
					meth.Statements.Add(
						new CodeSnippetStatement(code));
					this.CodeBesideCCU.Namespaces[0].Types[0].Members.Add(meth);
				}
			}
		}
		private void addPropertyForBObjectToCodeBeside(TypeProvider typeProvider,
			BusinessObject bobj, CodeTypeReference typeRefBObj, string varName)
		{
			_memberCreation.CreateProperty(this.FullClassName,
										   varName /*bobj.Name + Deployment.cBObjPropSuffix*/,
										   typeProvider.GetType(typeRefBObj.BaseType),
										   null,
										   true,
										   false,
										   false,
										   null,
										   false);
		}

		private object getSelectedItem()
		{
			object selectedItem = null;
			ISelectionService selectionService = GetService(typeof(ISelectionService)) as ISelectionService;
			if ( selectionService != null ) {
				selectedItem = selectionService.PrimarySelection;
			}
			return selectedItem;
		}
		private void setSelectedItem(object item)
		{
			ISelectionService selectionService = GetService(typeof(ISelectionService)) as ISelectionService;
			if ( selectionService != null ) {
				ArrayList al = new ArrayList();
				if ( item != null )
					al.Add(item);
				selectionService.SetSelectedComponents(al);
			}
		}

		#endregion

		#endregion

		#region Members for Human Activities
		//private OpenComposite.Base.Data.Structures.DsProcessStructure _dsHAProc = null;

		private void addHumanActivity(Repository.LogicalActivity logact, string url)
		{
			//if ( _dsHAProc == null ) return;
			if ( logact == null ) throw new ArgumentNullException("logact");
			if ( logact.ExtendedProperties == null ||
				 logact.ExtendedProperties.HumanComponentProperties == null ) {
				return;
			}
			//if ( _dsHAProc == null )
			//initProcessDS();
			// read service properties
			Repository.HumanComponentProperties props =
				logact.ExtendedProperties.HumanComponentProperties;
			// get process row
			//DsProcessStructure.processRow rowProc =
			//    _dsHAProc.process.Rows[0] as DsProcessStructure.processRow;
			//DsProcessStructure.process_activityRow rowProcAct = null;
			//if ( this.Workflow.ExtendedProperties.LogicalActivityProcessActivities.ContainsKey(logact.ID) ) {
			//    rowProcAct = _dsHAProc.process_activity.FindByproc_act_id(
			//        this.Workflow.ExtendedProperties.LogicalActivityProcessActivities[logact.ID]);
			//}
			//if ( rowProcAct == null ) {
			//    // set process activity row
			//    rowProcAct = _dsHAProc.process_activity.Addprocess_activityRow(
			//        rowProc,
			//        logact.Name,
			//        logact.Description,
			//        "", true, 86400, 86400, 86400, 0f, "0", true, "Activity", false, false, 0, 0, false,
			//        false, false, url, props.AssemblyName, props.FormName, "", "");
			//} else {
			//    rowProcAct.proc_act_nm = logact.Name;
			//    rowProcAct.proc_act_desc = logact.Description;
			//    rowProcAct.activityservice_url = url;
			//    rowProcAct.assembly_name = props.AssemblyName;
			//    rowProcAct.assembly_form_name = props.FormName;
			//}

			// set process activity participants
			#region remove all previous participants
			//removeParticipantsOfActivity(_dsHAProc.process_activity_email_participant, rowProcAct.proc_act_id);
			//removeParticipantsOfActivity(_dsHAProc.process_activity_organization_participant, rowProcAct.proc_act_id);
			//removeParticipantsOfActivity(_dsHAProc.process_activity_organization_unit_participant, rowProcAct.proc_act_id);
			//removeParticipantsOfActivity(_dsHAProc.process_activity_property_participant, rowProcAct.proc_act_id);
			//removeParticipantsOfActivity(_dsHAProc.process_activity_role_participant, rowProcAct.proc_act_id);
			//removeParticipantsOfActivity(_dsHAProc.process_activity_user_participant, rowProcAct.proc_act_id);
			//removeParticipantsOfActivity(_dsHAProc.process_activity_activity_owner_participant, rowProcAct.proc_act_id);
			#endregion
			foreach ( HumanComponentParticipant part in props.Participants ) {
				#region add participant to dataset
				switch ( part.Type ) {
					case ParticipantType.EmailParticipant:
						//_dsHAProc.process_activity_email_participant.Addprocess_activity_email_participantRow(
						//    rowProcAct, (byte)part.PartTypeCD, part.Additional1);
						break;
					case ParticipantType.PropertyParticipant:
						//_dsHAProc.process_activity_property_participant.Addprocess_activity_property_participantRow(
						//    rowProcAct, (byte)part.PartTypeCD, part.Display);
						break;
					case ParticipantType.Organization:
						//_dsHAProc.process_activity_organization_participant.Addprocess_activity_organization_participantRow(
						//    rowProcAct, part.ID, (byte)part.PartTypeCD);
						break;
					case ParticipantType.OrganizationUnit:
						//_dsHAProc.process_activity_organization_unit_participant.Addprocess_activity_organization_unit_participantRow(
						//    rowProcAct, part.ID, (byte)part.PartTypeCD);
						break;
					case ParticipantType.ParticipantRule:
						break;
					case ParticipantType.PartnerRule:
						break;
					case ParticipantType.PartnerRole:
						break;
					case ParticipantType.Role:
						//_dsHAProc.process_activity_role_participant.Addprocess_activity_role_participantRow(
						//    rowProcAct, part.ID, (byte)part.PartTypeCD);
						break;
					case ParticipantType.User:
						//_dsHAProc.process_activity_user_participant.Addprocess_activity_user_participantRow(
						//    rowProcAct, part.ID, (byte)part.PartTypeCD);
						break;
					default:
						break;
				}
				#endregion
			}
			//this.Workflow.ExtendedProperties.LogicalActivityProcessActivities[logact.ID] =
			//    rowProcAct.proc_act_id;
			//saveHumanActivityProcess();
		}
		private void removeParticipantsOfActivity(DataTable dtPartType, int idProcAct)
		{
			DataRow[] rows = dtPartType.Select("proc_act_id = " + idProcAct);
			foreach ( DataRow row in rows ) {
				dtPartType.Rows.Remove(row);
			}
		}
		private void initProcessDS()
		{
			//if ( this.Workflow.ExtendedProperties.ProcessID > 0 ) {
			//    try {
			//        _dsHAProc = Global.ProcessData.GetCompleteProcess(
			//            this.Workflow.ExtendedProperties.ProcessID.ToString(), this.Workflow.OrganizationId.ToString());
			//    } catch ( Exception ex ) {
			//        Debug.WriteLine("[InitProcessDS] " + ex.Message);
			//        this.Workflow.ExtendedProperties.ProcessID = -1;
			//        _dsHAProc = null;
			//    }
			//}
			//if ( _dsHAProc == null ) {
			//    _dsHAProc = new DsProcessStructure();
			//}
			//if ( _dsHAProc.process.Rows.Count == 0 ) {
			//    // add new process row
			//    DsProcessStructure.processRow rowProc =
			//        _dsHAProc.process.AddprocessRow(
			//            this.Workflow.Name,
			//            this.Workflow.OrganizationId,
			//            0,
			//            this.Workflow.Description,
			//            "", false, 0, 0, 0, false, "");
			//    // add process owner
			//    int userkey;
			//    if ( int.TryParse(Global.CurrentUser.UserKey, out userkey) ) {
			//        _dsHAProc.process_user_participant.Addprocess_user_participantRow(
			//            rowProc, userkey, (byte)5);
			//    }
			//}
		}
		private void saveHumanActivityProcess()
		{
			//            if ( _dsHAProc == null || _dsHAProc.process.Rows.Count == 0 ||
			//                 _dsHAProc.process_activity.Rows.Count == 0 )
			//                return;
			//            RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			//            Debug.Assert(repSvc != null);
			//            Dictionary<int, int> deletedRows = new Dictionary<int, int>();
			//            foreach ( KeyValuePair<int,int> lp in this.Workflow.ExtendedProperties.LogicalActivityProcessActivities ) {
			//                int logactid = lp.Key;
			//                int procactid = lp.Value;
			//                bool deleted = false;
			//                try {
			//                    LogicalActivity la = repSvc.GetItem<LogicalActivity>(logactid);
			//                    if ( la == null || la.IsDeleted )
			//                        deleted = true;
			//                } catch ( RepositoryItemDeletedException ) {
			//                    deleted = true;
			//                }
			//                if ( deleted ) {
			//                    deletedRows.Add(logactid, procactid);
			//                }
			//            }
			//            foreach ( KeyValuePair<int,int> lp in deletedRows ) {
			//                this.Workflow.ExtendedProperties.LogicalActivityProcessActivities.Remove(lp.Key);
			//                DsProcessStructure.process_activityRow row = _dsHAProc.process_activity.FindByproc_act_id(lp.Value);
			//                if ( row != null ) {
			//                    row.Delete();
			//                }
			//            }
			//SaveProcess:
			//            Hashtable htActIds;
			//            string procid = "";
			//            try {
			//                procid = Global.ProcessData.SaveProcess(
			//                    _dsHAProc,
			//                    this.Workflow.ExtendedProperties.ProcessID.ToString(),
			//                    this.Workflow.OrganizationId.ToString(),
			//                    Global.CurrentUser.UserKey,
			//                    ( this.Workflow.ExtendedProperties.ProcessID <= 0 ),
			//                    out htActIds);
			//            } catch ( Exception ex ) {
			//                Debug.WriteLine("[SaveHumanActivityProcess] " + ex.Message);
			//                if ( ex.Message.Contains("name you chose is already being used") ) {
			//                    DataTable dt = Global.ProcessData.GetProcesses(Global.CurrentUser.OrganizationID);
			//                    if ( dt != null && dt.Columns.Contains("proc_nm") ) {
			//                        foreach ( DataRow dr in dt.Rows ) {
			//                            if ( (string)dr["proc_nm"] == _dsHAProc.process[0].proc_nm ) {
			//                                Global.ProcessData.DeleteProcess(dr["proc_id"].ToString());
			//                                this.Workflow.ExtendedProperties.ProcessID = -1;
			//                                goto SaveProcess;
			//                            }
			//                        }
			//                    }
			//                    htActIds = null;
			//                    throw ex;
			//                } else {
			//                    htActIds = null;
			//                    throw ex;
			//                }
			//            }
			//            int idProc;
			//            if ( int.TryParse(procid, out idProc) ) this.Workflow.ExtendedProperties.ProcessID = idProc;

			//            foreach ( int oldid in htActIds.Keys ) {
			//                int[] keys = new int[this.Workflow.ExtendedProperties.LogicalActivityProcessActivities.Keys.Count];
			//                this.Workflow.ExtendedProperties.LogicalActivityProcessActivities.Keys.CopyTo(keys, 0);
			//                foreach ( int key in keys ) {
			//                    if ( this.Workflow.ExtendedProperties.LogicalActivityProcessActivities[key] == oldid ) {
			//                        this.Workflow.ExtendedProperties.LogicalActivityProcessActivities[key] =
			//                            (int)htActIds[oldid];
			//                    }
			//                }
			//            }
		}
		#endregion

		#region Helpers

		public void UpdateLogicalActivityIds()
		{
			_listLogActs = getCurrentLogicalActivityIds();
		}
		private List<int> getCurrentLogicalActivityIds()
		{
			List<int> lstLogActs = new List<int>();
			Activity[] activities = GetNestedActivities(Helpers.GetRootActivity(_workflow) as CompositeActivity);
			foreach ( Activity act in activities ) {
				LogicalCapabilityActivity lca = act as LogicalCapabilityActivity;
				LogicalEPActivity lea = act as LogicalEPActivity;
				DataAggregatorActivity daa = act as DataAggregatorActivity;
				RuleEvaluatorActivity rea = act as RuleEvaluatorActivity;
				LogicalInputActivity lia = act as LogicalInputActivity;
				LogicalMethodCallActivity lmca = act as LogicalMethodCallActivity;
				if ( lca != null ) {
					if ( !lstLogActs.Contains(lca.LogicalActivityId) )
						lstLogActs.Add(lca.LogicalActivityId);
				} else if ( lea != null ) {
					if ( !lstLogActs.Contains(lea.LogicalActivityId) )
						lstLogActs.Add(lea.LogicalActivityId);
				} else if ( daa != null ) {
					if ( !lstLogActs.Contains(daa.LogicalActivityId) )
						lstLogActs.Add(daa.LogicalActivityId);
				} else if ( rea != null ) {
					if ( !lstLogActs.Contains(rea.LogicalActivityId) )
						lstLogActs.Add(rea.LogicalActivityId);
				} else if ( lia != null ) {
					if ( !lstLogActs.Contains(lia.LogicalActivityId) )
						lstLogActs.Add(lia.LogicalActivityId);
				} else if ( lmca != null ) {
					if ( !lstLogActs.Contains(lmca.LogicalActivityId) )
						lstLogActs.Add(lmca.LogicalActivityId);
				}
			}
			return lstLogActs;
		}

		private static void AddObjectGraphToDesignerHost(IDesignerHost designerHost, Activity activity)
		{
			Guid Definitions_Class = new Guid("3FA84B23-B15B-4161-8EB8-37A54EFEEFC7");

			if ( designerHost == null )
				throw new ArgumentNullException("designerHost");
			if ( activity == null )
				throw new ArgumentNullException("activity");

			string rootSiteName = activity.QualifiedName;
			if ( activity.Parent == null ) {
				string fullClassName = activity.UserData[Definitions_Class] as string;
				if ( fullClassName == null )
					fullClassName = activity.GetType().FullName;
				rootSiteName = ( fullClassName.LastIndexOf('.') != -1 ) ? fullClassName.Substring(fullClassName.LastIndexOf('.') + 1) : fullClassName;
				designerHost.Container.Add(activity, rootSiteName);
			} else {
				designerHost.Container.Add(activity, activity.QualifiedName);
			}

			if ( activity is CompositeActivity ) {
				foreach ( Activity activity2 in GetNestedActivities(activity as CompositeActivity) )
					designerHost.Container.Add(activity2, activity2.QualifiedName);
			}
		}

		//private static Activity[] GetNestedActivities(CompositeActivity compositeActivity)
		//{
		//    if ( compositeActivity == null )
		//        throw new ArgumentNullException("compositeActivity");

		//    IList<Activity> childActivities = null;
		//    ArrayList nestedActivities = new ArrayList();
		//    Queue compositeActivities = new Queue();
		//    compositeActivities.Enqueue(compositeActivity);
		//    while ( compositeActivities.Count > 0 ) {
		//        CompositeActivity compositeActivity2 = (CompositeActivity)compositeActivities.Dequeue();
		//        childActivities = compositeActivity2.Activities;

		//        foreach ( Activity activity in childActivities ) {
		//            nestedActivities.Add(activity);
		//            if ( activity is CompositeActivity )
		//                compositeActivities.Enqueue(activity);
		//        }
		//    }
		//    return (Activity[])nestedActivities.ToArray(typeof(Activity));
		//}
		private static Activity[] GetNestedActivities(CompositeActivity compositeActivity)
		{
			if ( compositeActivity == null ) return new Activity[0];
			List<Activity> activities = new List<Activity>();
			foreach ( Activity act in compositeActivity.Activities ) {
				activities.Add(act);
				if ( act is CompositeActivity ) {
					activities.AddRange(WorkflowLoader.GetNestedActivities((CompositeActivity)act));
				}
			}
			return activities.ToArray();
		}

		internal static void DestroyObjectGraphFromDesignerHost(IDesignerHost designerHost, Activity activity)
		{
			if ( designerHost == null )
				throw new ArgumentNullException("designerHost");
			if ( activity == null )
				throw new ArgumentNullException("activity");
			if ( designerHost.RootComponent == null )
				return;
			try {
				designerHost.DestroyComponent(activity);
			} catch { }

			if ( activity is CompositeActivity ) {
				foreach ( Activity activity2 in GetNestedActivities(activity as CompositeActivity) ) {
					try {
						designerHost.DestroyComponent(activity2);
					} catch { continue; }
				}
			}
		}
		private void setActivityProperty(Activity activity, string propertyName, object value)
		{
			PropertyDescriptor prop = TypeDescriptor.GetProperties(activity).Find(propertyName, false);
			if ( prop == null ) {
				throw new MissingMemberException(
					string.Format("The activity \"{0}\" does not contain the property \"{1}\".",
						activity.Name, propertyName));
			}
			prop.SetValue(activity, value);
		}

		private void addPropertyToInterface(CodeTypeDeclaration type,
			string propType, string propName, bool hasGet, bool hasSet)
		{
			CodeMemberProperty prop = new CodeMemberProperty();
			prop.Name = propName;
			prop.Type = new CodeTypeReference(propType);
			prop.Attributes = 0;
			prop.HasGet = hasGet;
			prop.HasSet = hasSet;
			type.Members.Add(prop);
		}
		private void addPropertyToInterface(CodeTypeDeclaration type,
			Type propType, string propName, bool hasGet, bool hasSet)
		{
			CodeMemberProperty prop = new CodeMemberProperty();
			prop.Name = propName;
			prop.Type = new CodeTypeReference(propType);
			prop.Attributes = 0;
			prop.HasGet = hasGet;
			prop.HasSet = hasSet;
			type.Members.Add(prop);
		}

		#endregion

		#endregion
	}

	#region Internal Enum: ServiceGenerationType
	internal enum ServiceGenerationType
	{
		Unknown = 0,
		SystemWebService,
		WCFService,
		HumanActivityService,
		APIService,
		MessageQueueService
	}
	#endregion

	#region Class: Help
	[DataContract]
	internal class Help
	{
		[DataMember]
		public int i = 0;
		[DataMember]
		public string s = "";
		[DataMember]
		public double d = 0;
		[DataMember]
		public decimal dc = 0;
		[DataMember]
		public DateTime dt = default(DateTime);
	}
	#endregion

	#region Internal Class: LogicalRuleResultEPInfos
	internal class LogicalRuleResultEPInfos
	{
		public LogicalRuleResultEPInfos(LogicalRuleResultEndpoint ruleresultendpoint)
		{
			this.RuleResultEndpoint = ruleresultendpoint;
			this.ContractNamespace = "Contract";
			this.EndpointConfigName = null;
			this.Wsdl = null;
			this.Bindings = null;

			this.TypeRefLogActContract = null;
			this.InputTypes = null;
			this.OutputTypes = null;

			this.MethodInMap = null;
			this.MethodOutMap = null;
			this.MethodContract = null;
		}
		public LogicalRuleResultEndpoint RuleResultEndpoint;
		public string ContractNamespace;
		public string EndpointConfigName;
		public System.Web.Services.Description.ServiceDescription Wsdl;
		public Collection<System.ServiceModel.Channels.Binding> Bindings;

		public CodeTypeReference TypeRefLogActContract;
		public List<Type> InputTypes;
		public List<Type> OutputTypes;

		public CodeMemberMethod MethodInMap;
		public CodeMemberMethod MethodOutMap;
		public CodeMemberMethod MethodContract;

		public bool UseProxy
		{
			get { return ( this.RuleResultEndpoint.ProxyWebMethod != null ); }
		}
	}
	#endregion
}
